【问题标题】:Java beginner -Trying to let player quit the gameJava初学者-试图让玩家退出游戏
【发布时间】:2021-06-15 21:18:45
【问题描述】:

我是一个制作猜谜游戏的初学者,我试图让玩家通过猜测 -1 来退出游戏。目前,如果我输入 -1,它会显示太低并要求我继续猜测,玩家在猜到数字之前无法退出游戏。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    char choice;
    
    do {
        int randomNum = (int) (Math.random() * 100 + 1);
        int guess = 0;

        while (guess != randomNum) {

            System.out.println("Guess a number between 1-100");
            guess = scan.nextInt();

            if (guess > randoomNum) {
                System.out.println("Too high.");
            }
            else if (guess < randoomNum) {
                System.out.println("Too low.");
            }
            else if (guess > 0) {
                System.exit(0);
                System.out.println("GAME OVER");
                System.out.println("the number was " + randomNum + ".");
            }
            else {
                System.out.println("Correct! Well done!");
            }
        }
    
        System.out.println("\nPlay again? (Y/N)");
        choice = scan.next() .charAt(0);

    
    } while (choice == 'Y' | choice =='y');

    
    System.out.println("GAME OVER");
}

【问题讨论】:

  • guess = scan.nextInt();之后添加if (guess == -1) break;
  • @JohnnyMopp,它似乎应该打破嵌套循环,或者可能使用System.exit()
  • @AlexRudenko 好的。然后他们应该将else if (guess &gt; 0) 块中的内容移动到我拥有break 的位置。所以,真的只是在他们得到用户输入后将整个块向上移动。无论如何,它应该是else if (guess &lt; 0)。错字?
  • @JohnnyMopp 谢谢!
  • 在最后的 while 中,你应该使用逻辑或 ("||") 而不是位或。

标签: java loops do-while


【解决方案1】:

现有代码需要稍作修改:在与randomNum比较之前,应检查退出条件。

其他需要解决的问题:

  • input 用于Scanner 实例
  • 在打印再见消息后执行System.exit
Scanner input = new Scanner(System.in);
char choice;
    
do {
    int randomNum = (int) (Math.random() * 100 + 1);
    int guess = 0;

    while (guess != randomNum) {

        System.out.println("Guess a number between 1-100, or -1 to exit");
        guess = input.nextInt();
        
        if (guess == -1) {
            System.out.println("GAME OVER");
            System.out.println("the number was " + randomNum + ".");
            System.exit(0);
        }

        if (guess > randomNum) {
            System.out.println("Too high.");
        }
        else if (guess < randomNum) {
            System.out.println("Too low.");
        }
        else {
            System.out.println("Correct! Well done!");
        }
    }

    System.out.println("\nPlay again? (Y/N)");
    choice = input.next().charAt(0);

} while (choice == 'Y' || choice =='y');
   
System.out.println("GAME OVER");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多