0

我正在用 Java 创建一个 HiLo 猜谜游戏。到目前为止,我所做的一切都按预期工作,除了在最后提示用户再次玩时,随机数与前一个游戏保持不变。当用户选择玩新游戏时,如何使代码产生一个新的随机数?

    int answer  = (int)(Math.random() * 100 + 1);
    int guess = 0;
    int guessCount = 0;
    boolean playGame = true;
    String restart;
    Scanner scan = new Scanner(System.in);
    
while(playGame == true)
{
    while (playGame == true) 
    {
        System.out.println("Enter a number between 1 and 100: ");
        guess = scan.nextInt();
        guessCount ++;
        
        System.out.println(answer);
        
        if (guess < 1 || guess > 100) 
        {
            System.out.println("You have entered an invalid number.");
            guessCount --;
        } else if (guess == answer) 
        {
            System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
            break;
        } else if (guess > answer) 
        {
            System.out.println("You've guessed too high! Guess again: ");
        } else if (guess < answer)
        {
            System.out.println("You've guessed too low! Guess again: ");
        }
    }
    
    System.out.println("Would you like to play again? Y/N");
    restart = scan.next();
    
    if (restart.equalsIgnoreCase("Y")) 
    {
        playGame = true;
    } else if(restart.equalsIgnoreCase("N"))
    {
        System.out.println("Thank you for playing!");
        break;
    }
}
4

2 回答 2

0

变量“答案”中的值保持不变,因为变量是对您存储/初始化或分配的内容的引用。它本身并不操纵。answer = (int)(Math.random()*100+1)例如,您必须在游戏重新启动之前或之后重写代码。

于 2020-11-27T00:26:21.147 回答
0

您正在初始化answer循环之前的循环,它永远不会改变。answer当用户选择玩新一轮时,您必须分配一个新值。这不是我要写的代码,但这里是:

if (restart.equalsIgnoreCase("Y")) 
{
    answer  = (int)(Math.random() * 100 + 1);
}
于 2020-11-27T00:27:18.723 回答