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
If you like to stop your loop after the line, create your 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 delimiter that contains whitespace, the empty expression, but not the next line character.
This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.
Example:
1 2 3\n
will give the following tokens:
Integer(1), Integer(2), Integer(3), Noninteger(\n)
Thus the hasNextInt returns false.