I would like to accept 3 integers input from user. How can I ignore anything after the first integer in a line? For example, when I input 1 2 3
or 1 abc 3
, the int test[]
variable will only accept 1
and the remaining part of the line will be ignored.
Goal: Ignore(or clear) anything after the first integer (starting from the first white space), including whatever whitespace or char. If possible, it will be great to have warning to user to warn user that whitespace cannot be enter in the input. I am not finding solution for reading multiple integers from the same line.
This is what I have:
private final int[] test = new int[4]; // I just use 1-3
Scanner input = new Scanner(System.in);
System.out.print("1st Integer: ");
test[1] = input.nextInt();
System.out.print("2nd Integer: ");
test[2] = input.nextInt();
System.out.print("3rd Integer: ");
test[3] = input.nextInt();
For the above code, if I simply input an integer e.g. 1 enter 2 enter 3 enter
, it is okay. But when I input something like 1 2 3
(with white space between 3 integers), it simply output something like this:
1st Integer: 1 2 3
2nd Integer: 3rd Integer:
I want my code to be like this:
1st Integer: 1
2nd Integer: 2
3rd Integer: 3