所以在调用我将在下面发布的函数(在我的主文件中)后,在同一个main中创建一个新的扫描仪对象不起作用并给了我以下错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
将我链接到此代码中的最后一行:
int numHouse = 0;
int numSeed = 0;
System.out.println("Enter the total number of houses on the board: ");
Scanner houseInput = new Scanner(System.in);
numHouse = houseInput.nextInt();
在我调用该函数后立即放置(我稍后在上面的代码中关闭扫描仪)。当我注释掉调用该函数时,此扫描程序正常工作,因此该函数中的某些内容导致扫描程序出错。我花了好几个小时看但却无法解决它,如果有人能的话,我会非常感激。功能:
public void InitializePlayers() {
//change numPlayers to variable that contains number of players
boolean validInput = false;
do {
System.out.print("Enter Number of Players (1/2): ");
Scanner userInput = new Scanner(System.in);
int numPlayers = userInput.nextInt();
System.out.print("\n");
if(numPlayers == 1) {
//One Human Player, One AI Player
System.out.println("Single Player Selected");
validInput = true;
System.out.print("\n");
System.out.print("Enter Player One Name: ");
//Initialize Player 1
String p0_name = userInput.next();
Player Human1 = new Player(p0_name,0,false);
this.setPlayer0(Human1);
//Initialize AI
String AI_name = "Hal";
Player AI = new Player(AI_name,1,true);
this.setPlayer1(AI);
userInput.close();
}
else if(numPlayers == 2){
//Two Human Players
System.out.println("Two Players Selected");
validInput = true;
System.out.print("Enter Player One Name: ");
//Initialize Player 1
String p0_name = userInput.next();
Player Human1 = new Player(p0_name,0,false);
this.setPlayer0(Human1);
//Initialize Player 2
System.out.print("Enter Player Two Name: ");
String p1_name = userInput.next();
Player Human2 = new Player(p1_name,0,false);
this.setPlayer1(Human2);
userInput.close();
}
else {
System.out.println("Error, Player 1 Not set!");
userInput.close();
}
}while(!validInput);
}
(我在测试时总是输入2)我已经尝试删除do-while循环,但这并没有解决问题。谢谢
答案 0 :(得分:1)
如果可以使用一个扫描程序从System.in读取整个应用程序
,那就更好了关闭需要播放器的扫描器将关闭InputStream,这将导致此NoSuchElmentException.Better,如果您可以定义一个扫描器并在两个场合使用它进行输入
答案 1 :(得分:0)
正如另一个人所说,我终于找到了这个问题。一旦关闭InputStream就关闭扫描仪,因此无法再次使用它。我必须在我的主开始时制作一个扫描仪并将其传递给所有需要它的功能。我从每个函数中删除了所有关闭,并在main结束时关闭。