【发布时间】:2015-10-21 22:54:52
【问题描述】:
所以我一直在寻找一段时间来了解如何使用扫描仪来获取用户的输入。发生的情况是我在第一个扫描仪之后进入了一个无限循环。我尝试将第二个扫描仪的名称更改为读取而不是读取,但这并没有改变任何内容。在我关闭以尝试解决问题之前,我将 in.nextLine() 放在第一个扫描仪实例的末尾,但这似乎不起作用。不太清楚为什么会这样。
` private int compPlayInput(){
int comps = -1; // Initialize
Scanner in = new Scanner(System.in); // Start Scanner
//While the user input isn't between 0 and 2
while ((comps<0) || (comps>2)){
System.out.println("Turn: " + turnCount);
System.out.print("How many computer controlled players will there be: ");
//did the user input an integer?
if (in.hasNextInt()){
comps=in.nextInt();//change comps variable to the user's input
}
//The user hasn't entered an integer
else {
System.out.println("\n\n** ERROR: Enter an integer x that satisfies 0 <= x <= 2 **\n");
}
}
in.nextLine(); //It seems like this is supposed to fix it, but it doesn't.
in.close(); // close scanner
return comps;
}
/**
* Gets a player's guess
* @return the player's guess (int) between 0 and 4 inclusively
*/
private int getPlayerGuess(){
int guess = -1; //initialize
Scanner in = new Scanner(System.in); //start scanner
//While the user doesn't input an int between 0 and 4
while ((guess<0) || (guess>4)){
System.out.println("Turn: " + turnCount);
System.out.print("What is your guess: ");
//If the user input an integer
if (in.hasNextInt()){
//make guess = to next int
guess=in.nextInt();
}
else {
System.out.println("\n\n** ERROR: Enter an integer x that satisfies 0 <= x <= 4 **\n");
}
}
in.close(); // close scanner
return guess; //return guess
}`
这是eclipse中的输出:
Turn: 0
How many computer controlled players will there be: 1
Turn: 1
What is your guess:
** ERROR: Enter an integer x that satisfies 0 <= x <= 4 **
Turn: 1
What is your guess:
** ERROR: Enter an integer x that satisfies 0 <= x <= 4 **
...
不允许用户像询问有多少计算机玩家时那样输入猜测。我不知道该如何解决这个问题。
我将 in.next() 放入 else 语句中,但似乎我遇到了错误,因为没有任何内容可供扫描仪读取。我得到的新输出是
回合:0 将有多少计算机控制的玩家:1 回合:1 你的猜测是什么:
** 错误:输入一个满足 0 的整数 x
线程“main”中的异常 java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(未知来源)在 HW2TaylorZacharyGame.getPlayerGuess(HW2TaylorZacharyGame.java:114) 在 HW2TaylorZacharyGame.turn(HW2TaylorZacharyGame.java:52) 在 HW2TaylorZachary.main(HW2TaylorZachary.java:15)
【问题讨论】:
-
即使链接的问题使用
try/catch而不是if/else,也是同样的问题。
标签: java java.util.scanner infinite-loop