How to use .nextInt() and hasNextInt() in a while loop

后端 未结 3 2093
礼貌的吻别
礼貌的吻别 2020-11-29 12:51

So I want my program to read an input, which has some integers in one line, for example:

1 1 2

Then it should read every integer separately and print it in a

3条回答
  •  没有蜡笔的小新
    2020-11-29 13:23

    The hasNextInt call blocks until it has enough information to make the decision of "yes/no".

    Press Ctrl+Z on Windows (or Ctrl+D on "unix") to close the standard input stream and trigger an EOF. Alternatively, type in a non-integer and press enter.

    Console input is normally line-buffered: enter must be pressed (or EOF triggered) and the entire line will be processed at once.

    Examples, where ^Z means Ctrl+Z (or Ctrl+D):

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

    See also:

    • How do I get Java's hasNextInt() to stop waiting for ints without inputting a character?
    • hasNext() - when does it block and why?
    • Java Scanner hasNext() doesn't return false

提交回复
热议问题