gpt4 book ai didi

java - 嵌套 while 循环在嵌套循环完成之前执行顶部循环 - Java

转载 作者:行者123 更新时间:2023-11-30 08:01:51 24 4
gpt4 key购买 nike

我正在做四连子游戏练习。除了错误检查之外,一切正常。用户输入一个字符串,我需要首先检查它的长度和格式是否正确(嵌套 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] 更改为“x”并从粘贴到此处的整个代码的顶部开始,而不仅仅是嵌套 while 循环的顶部。

最佳答案

你的

 while (!validr && !validc);

condition 表示只要 validrvalidc 都为 false(即行号和列号都无效),内部循环就会继续。

您需要 validrvalidc 都为 true 才能退出内循环,因此您的条件应该是:

while (!validr || !validc);

即只要 validrvalidc 为 false,循环就会继续。

关于java - 嵌套 while 循环在嵌套循环完成之前执行顶部循环 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31801341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com