3

I get an infinite loop in this code

I'm just trying to get the user to reenter the integer just once in the while loop

Where is the problem?

System.out.print ("Enter a number: ");

while (!scan.hasNextInt())
  System.out.print ("reenter as integer: ");
  num = scan.nextInt();
4

4 回答 4

3

您的 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
于 2013-09-20T18:53:38.560 回答
3

Scanner#hasNextInt()方法不会将光标移过任何输入。因此,它将继续针对您提供的相同输入进行测试,因此如果它失败一次,它将继续失败。因此,如果您输入"abc"hasNextInt()则将继续针对 进行测试"abc",从而进入无限循环。

为此,您需要Scanner#next()在 while 循环中使用方法。

此外,您应该考虑使用一些最大尝试让用户输入正确的输入,这样如果用户继续传递无效输入,这不会进入无限循环。

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();
于 2013-09-20T18:53:41.047 回答
0

您没有大括号,因此 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
于 2013-09-20T19:17:23.537 回答
0

表达式“!scan.hasNextInt()”转换为“没有另一个我可以扫描的int”考虑循环“scan.hasNextInt()”,它转换为“还有另一个我可以扫描的int”

于 2013-09-20T18:50:40.373 回答