我正在进行Connect Four游戏练习。除错误检查外,一切正常。用户输入一个字符串,我需要首先检查它是否是正确的长度和格式(嵌套while循环),然后如果条目创建一个赢家来结束游戏(顶部while循环)。
但是,即使该条目无效,并且嵌套的while循环仍应循环,Java也会在外部while循环中执行其余代码。我在这里做错了什么?
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]
更改为&#34; x&#34;并从这里粘贴的整个代码的顶部重新开始,而不仅仅是嵌套的while循环的顶部。
答案 0 :(得分:1)
您
while (!validr && !validc);
条件意味着只要validr
和validc
都为假(即行号和列号都无效),内循环就会继续。
您需要validr
和validc
才能退出内循环,因此您的条件应为:
while (!validr || !validc);
即。只要validr
或validc
为假,循环就会继续。
答案 1 :(得分:0)
!(a&amp; b)=!a || !b “not(A和B)”与“(不是A)或(不是B)”
相同Demorgan的法律。 在你的程序中应用这个你的while循环应该是
while (!validr || !validc);