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

Therefore, I want my program to read input that has integers on one line, for example:

1 1 2

Then it has to read each integer separately and print it on a new line. The number of integers the program should read is not specified in advance, so I'm trying to use a while loop that 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 doesn't work right because the loop never ends, it just wants the user to enter more integers. What am I missing here?

+3


source to share


3 answers


Your scanner basically waits until the end of the file appears. And if you use it in the console, which doesn't happen, it will continue to work. Try reading integers from the file, you will notice that your program will terminate.



If you are not familiar with reading from a file, create test.txt

in your project folder and use Scanner scan = new Scanner(new File("test.txt"));

with your code.

+1


source


Blocking hasNextInt

blocks until there is enough information to make a yes / no decision.

Press Ctrl + Z on Windows (or Ctrl + D on "unix") to close standard input and call EOF . Alternatively, enter a non-integer number and press enter.

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

Examples where ^ Z stands for 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:

+5


source


If you like to stop the loop after the line, create Scanner

like this:

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

}

      

The trick is to define a separator that contains spaces, an empty expression, but not the next character in the line. So Scanner

sees \n

followed by a delimiter (nothing) and entry stops after hitting return.

Example: 1 2 3 \ n will output the following tokens: Integer (1), Integer (2), Integer (3), Noninteger (\ n) So hasNextInt

returns false.

0


source







All Articles