-1

我是一名学生,目前正在学习基本的 Java 课程。我正在编写一个代码,该代码要求用户输入游戏以“开始”和“退出”。所以我分别选择了字符串“S”和“Q”。如果用户输入 S,则游戏继续。如果用户输入 Q,程序会显示“感谢播放”或其他内容。如果用户输入的不是 S 和 Q,程序会再次询问,直到它得到一个有效的输入。除了错误检查部分,我几乎把所有东西都弄对了。任何可能的建议来修复我的代码?

先感谢您!:)

(部分代码)

    Scanner scan = new Scanner(System.in);
    String userInput;
    boolean game = false;

    System.out.println("Welcome to the Game! ");
    System.out.println("Press S to Start or Q to Quit");

    userInput = scan.nextLine();

    if (userInput.equals("S")){
        game = true;
    } else if (userInput.equals("Q")){
        game = false;
    } else {
        do {
            System.out.println("Invalid input! Enter a valid input: ");
            userInput = scan.nextLine();
        } while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // I'm not sure if this is valid???
    }

    if (userInput.equals("S")){
        ///// Insert main code for the game here////
    } else if (userInput.equals("Q")){
    System.out.println("Thank you for playing!");
    }
4

2 回答 2

2

您正在创建一个无限循环:

while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // always true

要使这种情况成立,您需要一个等于"S" to的输入"Q"。很容易看到应用德摩根定律

while (!("S".equals(userInput)) && "Q".equals(userInput))); // always true

显然,这不会发生。

你可能想要:

while (!"S".equals(userInput)) && (!"Q".equals(userInput));
于 2016-07-23T13:26:36.403 回答
0

我还不能对答案投票,但前一个是正确的。

打破逻辑:

input = "Z"
while( !(S==Z) || !(Q==Z) ) -> while( !(F) || !(F) ) -> while( T || T ) -> repeat

input = "Q"
while( !(S==Q) || !(Q==Q) ) -> while( !(F) || !(T) ) -> while( T || F ) -> repeat

切换到“and”会使案例 #2 工作。你对你的“游戏”布尔值做了什么吗?如果用户进入 while 循环,则布尔值将始终为 false。

于 2016-07-23T13:35:55.423 回答