I need to validate that the user inputs two integers and as such, I need to continue asking him for input until he provides both inputs that are integers. Not sure how to implement it, but I came up with something like that, but now struggling to implement the part that checks if coord1 and coord2 get correct types. If not, it of course gives me the NumberFormatException
:
while (true) {
System.out.print("Enter the coordinates: ");
int coord1 = Integer.parseInt(scanner.next());
int coord2 = Integer.parseInt(scanner.next());
if (coord1 < 1 || coord1 > 3 || coord2 < 1 || coord2 > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
} else if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
continue;
}
break;
}
Can I solve it without using try-catch
, since I haven't learned that yet, or is this the only way?
Thank you in advance and sorry, since I'm still learning Java syntax and ways of validation.
Instead of checking manually if the input is the right type, you could rely on the Scanner
's methods hasNextInt()
and nextInt()
.
The method hasNextInt()
returns true
if the next input can be interpreted as an int
value, while nextInt()
scans the next token of the input as an int. Keep in mind that after reading a non-string value, you might want to place an extra nextLine()
, for further details read the following question.
Here, I've included a sample main with your code re-written. As a side note, avoid declaring fields in loops.
public class Main {
public static void main(String[] args) {
int coord1 = 0, coord2 = 0;
do {
coord1 = readCoordinate("Enter first coordinate: ");
coord2 = readCoordinate("Enter second coordinate: ");
//Showing an error message if the coords refer to an occupied cell
if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
}
} while (cellOccupied(field, coord1, coord2));
}
private static int readCoordinate(String message) {
int coord;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(message);
if (scanner.hasNextInt()) {
coord = scanner.nextInt();
//getting rid of the new line character after reading the int
scanner.nextLine();
//Checking coordinate value
if (coord < 1 || coord > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
}
} else {
//assigning an undesired value (since your coords must be between 1 and 3
coord = 0;
//getting rid of the wrong user input
scanner.nextLine();
//Showing an error message
System.out.println("Please enter an int value");
//Skipping directly to the loop's condition
continue;
}
break;
}
return coord;
}
}