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

Nested while loop executing top loop before nested loop completes- Java

我正在做 Connect Four 游戏练习。除错误检查外,一切正常。用户输入一个字符串,我需要先检查它的长度和格式是否正确(嵌套的while循环),然后如果条目创建了一个获胜者来结束游戏(top while-loop)。

但是,即使条目无效,嵌套的 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);

条件意味着只要validrvalidc都为假(即行号和列号都无效),内循环就会继续。

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

while (!validr || !validc);

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

!(a&b)= !a || !b "not (A and B)" 与“(非 A)或(非 B)”相同

德摩根定律。 将此应用到您的程序中,您的 while 循环应该是

while (!validr || !validc);