我正在尝试创建一个猜谜游戏,但无法正常工作

时间:2020-06-01 13:25:15

标签: java

我正在尝试创建一个猜游戏,您必须猜一个介于1到10之间的数字,但是如果输入0,那么它将退出程序。我设法使其工作(减去退出部分),因此我尝试添加下一步,即退出功能。我假设如果您获得正确的数字,则首先根据其他顺序,然后说“您赢了游戏”,这就是发生的情况,但是,如果答案错误,它就会退出。我试图让它仅在用户键入0时退出,但无论您键入什么数字都退出(只要不是正确的数字)(我花了很多小时尝试了不同的事情,但似乎没有工作。这是代码:

public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);           

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber)

        System.out.println("You won the game");

    else if (guess == 0)

        System.exit(0);

    else

        System.out.println("Invalid guess!");
}

2 个答案:

答案 0 :(得分:0)

此处此函数未递归运行。因此它只运行一次并退出。如下更改代码,然后尝试。

public static void main(String[] args) {
    guessingGame();
}

public static void guessingGame() {

    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);           

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber) {

        System.out.println("You won the game");
        guessingGame();
    }
    else if (guess == 0)

        System.exit(0);

    else {

        System.out.println("Invalid guess!");
        guessingGame();
    }
}

答案 1 :(得分:0)

看看这个:

 public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);
    boolean playAgain=true;
    System.out.print("Guess a number between 1 and 10: ");
    do {
       Scanner keyboard = new Scanner(System.in);
       guess = keyboard.nextInt();

       if (guess == secretNumber) {
           System.out.println("You won the game");
           playAgain = false;
       }
       else if (guess == 0)
           System.exit(0);
       else {
           System.out.println("Invalid guess!");
           System.out.print("Try again,Guess a number between 1 and 10:");
       }
   }while(playAgain);
}