扫描仪方法打开和关闭两次

在一个类中,我有两种使用扫描器类的不同方法。我为第一个方法创建了一个扫描程序对象的新实例,然后在第一个方法的结尾将其关闭…然后在第二个方法中创建了一个对象(具有不同名称)的新实例,最后在此方法的结尾。

除非我打开扫描仪一次,然后关闭扫描仪,否则它将无法工作并返回错误。扫描器类的双重用途似乎不起作用。我究竟做错了什么?

这是我的两种返回错误的方法…

public void GameSetup(){

//intro to the program and what the user should expect to do

Scanner in = new Scanner(System.in);

out.println("Let's play a little baseball game. Type down the scores for each team at the end of each inning to determine the winner!" +

"\nFor each inning enter the score for the first team, hit space and enter the score for the second team.\nFirst, let's enter the team names:");

//Console will ask for the team names.

out.println("What is the name of team 1?");

team1Name = in.nextLine(); //Read team name 1

out.println("What is the name of team 2?");

team2Name = in.nextLine(); //Read team name 2

in.close();//close the scanner

}

public void GetScores() {//this method will make the console ask for the scores for each innings

Scanner input = new Scanner(System.in);

out.println("What is the score at the end of 1st inning? (team 1 score <space> team 2 score)"); //The console asks to enter scores for each team

team1Array[0] = input.nextInt(); //Read an integer for team 1 inning 1

team2Array[0] = input.nextInt(); //Read an integer for team 2 inning 1

out.println("What is the score at the end of 2nd inning? (team 1 score <space> team 2 score)");

input.close();

}

回答:

您应该将Scanner声明为类变量,因为您已经在gameSetup()方法中关闭了扫描仪。例:

 public class Game{

Scanner in = new Scanner(System.in);

public void GameSetup(){

//insert code here DO NOT CLOSE SCANNER....

}

public void GetScores() {

//your code here.........

in.close();

}

}

否则,您可以做的是在每个方法中声明一个扫描器并关闭作用域。

以上是 扫描仪方法打开和关闭两次 的全部内容, 来源链接: utcz.com/qa/401587.html

回到顶部