在 HiLo 猜谜游戏结束时产生新随机数的问题
Problem producing a new random number at the end of HiLo guessing game
我正在 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;
}
}
变量 'answer' 中的值保持不变,因为变量是对您存储/初始化或分配的内容的引用。它本身不操纵。您必须重写代码,例如answer = (int)(Math.random()*100+1)
在游戏重新开始之前或之后。
你在循环之前初始化 answer
,它永远不会改变。当用户选择玩新一轮时,您必须分配 answer
一个新值。这不是我要写的代码,但它是:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}
我正在 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;
}
}
变量 'answer' 中的值保持不变,因为变量是对您存储/初始化或分配的内容的引用。它本身不操纵。您必须重写代码,例如answer = (int)(Math.random()*100+1)
在游戏重新开始之前或之后。
你在循环之前初始化 answer
,它永远不会改变。当用户选择玩新一轮时,您必须分配 answer
一个新值。这不是我要写的代码,但它是:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}