I am trying to validate input from a user.The user puts in Y coordinate a letter between (A-J) and x coordinate a number between (1-9).I can validate the y coordinate but am having trouble validating the x coordinate. I want it so if the user puts in something other than a number between 1 and 9 it keeps asking the user for valid input.
do {
// inner loop checks and validates user input
do {
System.out.println("Enter X Co-Ord (A-J), or Q to QUIT");
letter = input.next().toUpperCase(); // upper case this for
// comparison
if (letter.equals("Q"))
break; // if user enters Q then quit
String temp = "ABCDEFGHIJ";
while (temp.indexOf(letter) == -1) {
validString = false;
System.out.println("Please enter a valid input");
letter = input.next().toUpperCase();
col = temp.indexOf(letter);
}
if (temp.indexOf(letter) != -1) {
validString = true;
col = temp.indexOf(letter);
}
try {
System.out.println("Enter Y Co-Ord (0-9)");
row = input.nextInt();
} catch (InputMismatchException exception) {
validInt = false;
System.out.println("Please enter a number between 1 -9");
}
catch (Exception exception) {
exception.printStackTrace();
}
valuesOK = false; // only set valuesOK when the two others are
// true
if (validString && validInt) {
valuesOK = true;
}
} while (!valuesOK); // end inner Do loop
The output is:
Enter X Co-Ord (A-J), or Q to QUIT
d
Enter Y Co-Ord (0-9)
h
Please enter a number between 1 -9
Enter X Co-Ord (A-J), or Q to QUIT
Enter Y Co-Ord (0-9)