在我提示用户再次玩游戏后,游戏将返回到之前的随机数,而不是重新启动



猜谜游戏试图提示用户再次玩。

我将其设置为while循环,但由于某种原因,它一直使用与前一个游戏相同的数字。为什么?我是否必须向 while 循环添加更多详细信息?

public class Guessing_zulueta {

public static int getOneInt() {
    //we will get one integer from the keyboard
    Scanner in = new Scanner(System.in);
    System.out.printf("Enter an integer: ");
    return in.nextInt();
}

public static int random = getRand();
public static final int MAX = 100;

public static int getRand() {
    Random randGenerator = new Random();
    int x = randGenerator.nextInt(MAX);
    return x;
}
public static void main(String[] args) {//here is my problem
    while (true){
        guessingGame();
    System.out.println("Do you wish to play again? (1 for yes, -1 for no: ");
    Scanner scan2 = new Scanner(System.in);
    int val = scan2.nextInt();
    if (val == 1)
        guessingGame();
    if (val == -1)
        break;
    }
}
public static void guessingGame() {
        int input = getOneInt();
        if (input == random) {
            System.out.println("Congratulations");
        }
        if (input > random) {
            System.out.println("Too big.");
            guessingGame();
        }
        if (input < random) {
            System.out.println("Too small.");
            guessingGame();
        }
}
}
加载

类时,您只分配一次 random 的值。要在每次玩游戏时分配一个新的随机数,您需要在调用 guessingGame 之前分配它。

我还稍微修改了你的循环;以前,如果用户键入1,你会调用guessingGame()然后在循环开始时再次调用它。现在,如果用户键入 1(或除 -1 以外的任何内容),它只会调用它一次。

public static void main(String[] args) {
    while (true) {
        random = getRand();
        guessingGame();
        System.out.println("Do you wish to play again? (1 for yes, -1 for no: ");
        Scanner scan2 = new Scanner(System.in);
        int val = scan2.nextInt();
        if (val == -1) {
            break;
        } else {
            // Any other value will continue to loop and play another game.
        }
    }
}

相关内容

最新更新