我正在做《Connect Four》游戏练习。除错误检查外,一切正常。用户输入一个字符串,我需要首先检查它的长度和格式是否正确(嵌套while-loop),然后检查条目是否创建了一个赢家来结束游戏(顶部while-loop)。
但是,即使条目无效,嵌套while-loop应该仍在循环,Java也会在外部while-loop中执行其余代码。我哪里做错了?
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);
}
}
它将显示抛出的任何异常的错误消息,但它也会将board[1][1]
更改为"x",并从粘贴在这里的整个代码的顶部开始,而不仅仅是嵌套while-loop的顶部。
您的
while (!validr && !validc);
条件表示只要validr
和validc
都为假(即行号和列号都无效),内循环将继续进行。
您需要validr
和validc
都为真才能退出内循环,因此您的条件应该是:
while (!validr || !validc);
。只要validr
或validc
为假,循环就会继续。
!(a&b)= !a ||"非(A和B)"等同于"(非A)或(非B)"
dm定律里。在你的程序中应用它你的while循环应该是
while (!validr || !validc);