This question already has an answer here: How to use java.util.Scanner to correctly read user input from System.in and act on it? (1 answer) Closed 3 years ago.
I'm taking user input from System.in using a java.util.Scanner. It is for a Tic Tac Toe game. The input is for 2 coordinates and it should look like this: 1 1 or 1 2 etc, two ints separated by space. I need to validate each one of them for things like:
It must be a non-negative number
It must be from 1-3
... etc
I have tried this approach but this is suitable for one value. What would be the best way to validate both values(for int type)?
do {
System.out.println("Enter the coordinates: ");
while (!scanner.hasNextInt()) {
System.out.println("You should enter numbers!");
scanner.next(); // this is important!
}
if(scanner.nextInt() > 3 || scanner.nextInt()<1 ) {
coord1 = scanner.nextInt();
}else{
System.out.println();
}
} while (coord1 !=0);
System.out.println("Thank you! Got " + coord1);