【问题标题】:How to use .nextInt() and hasNextInt() in a while loop如何在 while 循环中使用 .nextInt() 和 hasNextInt()
【发布时间】:2014-12-21 09:42:30
【问题描述】:

所以我希望我的程序读取一个输入,该输入在一行中有一些整数,例如:

1 1 2

然后它应该分别读取每个整数并在新行中打印。程序必须读取的整数个数没有提前给出,所以我要做的是使用一个while循环,它在没有更多整数要读取后结束。这是我写的代码:

while (scan.hasNextInt()) {
    int x = scan.nextInt();
    System.out.println(x);
}

但它不能正常工作,因为循环永远不会结束,它只是希望用户输入更多的整数。我在这里想念什么?

【问题讨论】:

    标签: java input while-loop java.util.scanner


    【解决方案1】:

    hasNextInt 调用阻塞,直到它有足够的信息来做出“是/否”的决定。

    Ctrl+Z on Windows (or Ctrl+D on "unix") 关闭standard input stream 并触发EOF。或者,输入一个非整数并按回车

    控制台输入通常是行缓冲的:必须按下回车键(或触发​​ EOF),并且将立即处理整行

    示例,其中 ^Z 表示 Ctrl+Z(或 Ctrl+D):

    1 2 3<enter>4 5 6^Z   -- read in 6 integers and end because stream closed
                          -- (two lines are processed: after <enter>, after ^Z)
    1 2 3 foo 4<enter>    -- read in 3 integers and end because non-integer found
                          -- (one line is processed: after <enter>)
    

    另见:

    【讨论】:

      【解决方案2】:

      您的扫描仪基本上会等到文件结尾进入。如果您在控制台中使用它,则不会发生这种情况,因此它将继续运行。尝试从文件中读取整数,您会注意到您的程序将终止。

      如果您不熟悉从文件中读取,请在您的项目文件夹中创建一个test.txt 并将Scanner scan = new Scanner(new File("test.txt")); 与您的代码一起使用。

      【讨论】:

        【解决方案3】:

        如果您想在该行之后停止循环,请像这样创建您的 Scanner

        public static void main(final String[] args) {
            Scanner scan = new Scanner(System.in).useDelimiter(" *");
            while (scan.hasNextInt() && scan.hasNext()) {
                int x = scan.nextInt();
                System.out.println(x);
            }
        
        }
        

        诀窍是定义一个包含空格、空表达式但不包含下一行字符的分隔符。 这样Scanner 会看到\n 后跟一个分隔符(无),并且输入在按回车后停止。

        示例: 1 2 3\n 将给出以下令牌: 整数(1)、整数(2)、整数(3)、非整数(\n) 因此hasNextInt 返回 false。

        【讨论】:

          猜你喜欢
          • 2014-03-26
          • 1970-01-01
          • 2016-04-06
          • 1970-01-01
          • 1970-01-01
          • 2016-01-10
          • 2017-09-11
          • 1970-01-01
          相关资源
          最近更新 更多