首页 > 解决方案 > 使用 printf() 和 nextInt() 方法显示时,Scanner hasNext() 无限循环

问题描述

我有这段代码在 do-while 循环中询问姓名和年龄:

public class Test1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        do  {
            System.out.print("Enter name & age: ");
            System.out.printf("%s %d",
                        scanner.next(), scanner.nextInt());
        } while (scanner.hasNext());
    }
}

它输出:

Enter name & age: test 6
test 6

然后似乎对我的输入没有反应,虽然它应该在第三行重复了这个问题。这里有什么问题?

标签: java

解决方案


java.util.Scanner.hasNext() 方法 如果此扫描器的输入中有另一个标记,则返回 true。此方法可能会在等待输入扫描时阻塞。扫描仪不会超过任何输入。阅读更多

为了避免被 hasNext() 阻塞,你可以简单地传递 true for 循环条件。

import java.util.Scanner;
public class Test1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        do  {
            System.out.print("Enter name & age: ");
            System.out.printf("%s %d", scanner.next(), scanner.nextInt());
        } while (true);
    }
}

推荐阅读