我在这段代码中遇到了无限循环
我只是想让用户在while循环中重新输入整数一次
问题出在哪里?
System.out.print ("Enter a number: ");
while (!scan.hasNextInt())
System.out.print ("reenter as integer: ");
num = scan.nextInt();
我在这段代码中遇到了无限循环
我只是想让用户在while循环中重新输入整数一次
问题出在哪里?
System.out.print ("Enter a number: ");
while (!scan.hasNextInt())
System.out.print ("reenter as integer: ");
num = scan.nextInt();
你的while循环实际上没有消耗它所看到的内容。你需要消耗非整数输入:
while (!scan.hasNextInt()) {
System.out.print ("reenter as integer: ");
scan.next(); // Consumes the scanner input indiscriminately (to a delimiter)
}
num = scan.nextInt(); // Consumes the scanner input as an int
Scanner#hasNextInt()
方法不会将光标移动到任何输入之后。因此,它将继续针对您提供的相同输入进行测试,并且如果一次失败,则会继续失败。所以,如果您输入 "abc"
,那么 hasNextInt()
将继续针对 "abc"
进行测试,从而进入无限循环。
您需要在 while 循环中使用 Scanner#next()
方法来解决这个问题。
此外,您应该考虑为用户输入正确的最大尝试次数,以防止如果用户继续传递无效输入,程序进入无限循环。
int maxTries = 3;
int count = 0;
while (!scan.hasNextInt()) {
if (++count == maxTries) {
// Maximum Attempt reached.
// throw some exception
}
System.out.print ("reenter as integer: ");
scan.next(); // Move cursor past current input
}
num = scan.nextInt();
你没有花括号,所以 while 循环会一直循环 System.out.print 语句而永远不会退出。
如果你按原样添加花括号,当输入非整数时,读取 int 将失败。
要正确读取整数,你必须循环“询问”下一个标记,然后验证它是否为 int。
$cat Wt.java
import java.util.*;
class Wt {
public static void main( String ... args ) {
Scanner s = new Scanner(System.in);
System.out.print("Write a number: ");
while ( !s.hasNextInt()) {
System.out.print("Write a number: ");
s.next(); // <-- ask for the next and see if that was an int
}
int n = s.nextInt();
System.out.println("The number was: " + n );
}
}
$javac Wt.java
$java Wt
Write a number: one
Write a number: two
Write a number: tres
Write a number: 1.1
Write a number: f
Write a number: 42
The number was: 42
表达式“!scan.hasNextInt()”的翻译是“没有其他整数可以扫描”。考虑循环使用“scan.hasNextInt()”,它的翻译是“有另一个整数可以扫描”。