Java Scanner类hasNextInt()方法似乎允许十进制数通过,或者它';这是由别的原因引起的。
唯一有效的输入必须是数字1、2、3和4。如果我输入一个字符串,它不会接受它。如果我输入的数字大于4,它将不接受。然而,如果我进入2.3或其他版本,程序就会崩溃。我看不出是什么导致了这一点,因为2.3不是整数,我不知道它是如何通过Scanner中的hasNextInt()方法的。有人解释一下吗?对于输入Java Scanner类hasNextInt()方法似乎允许十进制数通过,或者它';这是由别的原因引起的。,java,java.util.scanner,Java,Java.util.scanner,唯一有效的输入必须是数字1、2、3和4。如果我输入一个字符串,它不会接受它。如果我输入的数字大于4,它将不接受。然而,如果我进入2.3或其他版本,程序就会崩溃。我看不出是什么导致了这一点,因为2.3不是整数,我不知道它是如何通过Scanner中的hasNextInt()方法的。有人解释一下吗?对于输入2.,第一个int是2,因此执行playGame(),但是done仍然是false,因为时(!done)循环选项。在上再次调用nextInt(),这不是int 因此出现了异常。对于第一个输入,您只需
2.
,第一个int是2
,因此执行playGame()
,但是done
仍然是false
,因为时(!done)
循环选项。在
上再次调用nextInt()
,这不是int
因此出现了异常。对于第一个输入,您只需检查
choice.hasnetint()
。第二轮不检查。将支票移动到while
循环中,使其如下所示:
Scanner choice = new Scanner(System.in);
while(!choice.hasNextInt()) {
System.out.println("Invalid input");
choice.next();
}
// Carry out appropriate method relating to user choice
boolean done = false; // Loop is not finished
while (!done) {
int i = choice.nextInt(); // Save the user's choice as int i
/*
* A switch statement here would probably be more elegant but this works too
* Problem: If the user inputs a non-integer number e.g. 2.3 the program explodes :(
*/
if (i == 1) {
newGame(); // Call newGame method
} else if (i == 2) {
playGame(); // Call playGame method
} else if (i == 3) {
viewResults(); // Call viewResults method
} else if (i == 4) {
done = true; // If user quits, the loop is done
quitGame(); // Call quitGame method
} else {
System.out.println("Invalid input");
}
}
你能发布stacktrace吗?如果输入确实是
2.3
开始,则hasnetint()
将返回false
。要更正它,请将while(!choice.hasnetint())
循环移动到while(!done)
循环中。@Vakh,with2.
它还返回false
。
boolean done = false;
while (!done) {
while(!choice.hasNextInt()) {
System.out.println("Invalid input");
choice.nextLine(); // drop entire line, not just next token
}
int i = choice.nextInt();
// ...
}