Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

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

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 new line. The number of integers the program has to read is not given in advance, so what I am trying to do is use a while loop, which ends after there are no more integers to read. This is the code I wrote:

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

but it's not working correctly, because the loop never ends, it just wants the user to input more integers. What am I missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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>)

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...