I'm working on a Connect Four game exercise. Everything is working except error checking. The user inputs a string, and I need to check first if it is the right length and format (nested while-loop), and then if the entry creates a winner to end the game (top while-loop).
However, even if the entry isn't valid, and the nested while-loop should still be looping, Java executes the rest of the code in the outer while-loop. What am I doing wrong here?
while (true) {
// get row and column from user
int row=1, column=1;
boolean validr = false, validc = false;
do {
System.out.print("Type the row and column you would like to drop your chip, separated by a space: ");
String drop = keyboard.nextLine();
// check that input is proper length
if(drop.length() == 3 && drop.contains(" ")) {
int space = drop.indexOf(" ");
// check if row is integer
try {
int testrow = Integer.parseInt(drop.substring(0, space));
//check if between 1 and 6
if (testrow > 0 && testrow < 7) {
row = Integer.parseInt(drop.substring(0, space));
validr = true;
} else {
System.out.println("Whoops, that row isn't valid!");
}
} catch (NumberFormatException ex) {
System.out.println("Make sure you're typing valid row and column numbers!");
}
// check if column is valid
try {
int testcolumn = Integer.parseInt(drop.substring(space+1));
//check if between 1 and 7
if (testcolumn > 0 && testcolumn < 8) {
column = Integer.parseInt(drop.substring(space+1));
validc = true;
} else {
System.out.println("Whoops, that column isn't valid!");
}
} catch (NumberFormatException ex) {
System.out.println("Make sure you're typing valid row and column numbers!");
}
} else {
System.out.println("Remember, type the row number, followed by a space, and then the column number.");
}
} while (!validr && !validc);
// change selected array value to 'x'
board[row-1][column-1] = "x";
// check if there is now a winner
if (checkBoard(board) == true) {
printBoard(board);
System.out.println("Congratulations! You got four in a row!");
break;
}
else {
printBoard(board);
}
}
It will display the error message for whichever exception was thrown, but it will also change board[1][1]
to "x" and start over at the top of the whole code pasted here, instead of just the top of the nested while-loop.
Your
while (!validr && !validc);
condition means that the inner loop will continue as long as both validr
and validc
are false (i.e. both the row number and column number are invalid).
You need both validr
and validc
to be true in order to exit the inner loop, so your condition should be :
while (!validr || !validc);
i.e. the loop will continue as long as either validr
or validc
is false.