I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
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;
}
}
Aucun commentaire:
Enregistrer un commentaire