我的while循环不会停止休息?

时间:2017-05-14 21:35:19

标签: java eclipse while-loop

if (sum < 6) {
    System.out.println("You win");
    System.out.println();
    // Does the user want to retry?
    System.out.print("Would you like to retry?(Y or N) : ");
    String retry = input.nextLine();

    while (true) {
        // If they say y or Y, roll again
        if (("y".equals(retry)) || ("Y".equals(retry))) {
            roll();
        // Check for anything other than y and Y
        } else if (("n".equals(retry)) || ("N".equals(retry))) {
            System.out.println("Closing");
            break;
        } else if (!("y".equals(retry)) || !("Y".equals(retry))) {
            System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
            retry = input.nextLine();
            System.out.println();

        }
    }
} else if (sum > 6) {
    System.out.println("You lose");
    System.out.println();
    System.out.print("Would you like to retry?(Y or N) : ");
    String retry = input.nextLine();
    while (true) {
        if (("y".equals(retry)) || ("Y".equals(retry))) {
            roll();
        } else if (("n".equals(retry)) || ("N".equals(retry))) {
            System.out.println("Closing");
            break;
        } else if (!("y".equals(retry)) || !("Y".equals(retry))) {
            System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
            retry = input.nextLine();
            System.out.println();
        }
    }
}

我正在尝试制作一个骰子游戏,当用户输入"y""Y"时,游戏将继续滚动骰子。我还希望它在用户输入"Closing""n"时停止游戏并说出"N"

问题是,当用户输入"n""N"时,它会打印出"Closing",但循环不会停止,游戏会再次滚动骰子。当用户输入"n""N"时,如何让while()循环停止?

以下是用户选择停止游戏时的输出("n" or "N")

you like to retry?(Y or N) : n
Closing
Rolling...
You rolled : 1 & 4
Sum = 5
You win

对不起这个基本问题,我是编程新手。

1 个答案:

答案 0 :(得分:5)

将行String retry = input.nextLine();移动到while循环(两个if分支中)。目前,您只需读入一个输入,然后一遍又一遍地比较不变的输入。