I am trying to adapt my dice program using a while loop so that after the 1st game has finished the user has a choice in entering 'y' (yes) to restart the game or 'no' in which case the program will print a "game over" statement. I also want to validate that the user has entered either 'y' or 'n' (non-case sensitive using .toLowerCase() method) and if they haven't, print an error statement and continue to ask for user entry until the correct entry is made. I have attempted to experiment with a while loop, an if-else clause and .equals() methods to no avail.
See "//play again?"
Here is my code:
public static void main(String args[]) {
String replay = "y";
Scanner input = new Scanner (System.in);
while(replay.equals("y"))
{
//roll one
int rNum1 = (int)(Math.random() * 11); //declare random roll one, gives result between 1 and 10
//print roll one
System.out.println("You roll the 10-sided die.");
System.out.println("It lands on " + rNum1 + ".");
System.out.println(); //space
//User guess
System.out.println("Will a second die roll higher or lower?");
System.out.println("To guess higher enter [1], or to guess lower, enter [2].");
//roll two
int rNum2 = (int)(Math.random() * 11); //declare random roll two
int guess = input.nextInt(); //user's guess / HiLo
//invalid user entry
while(guess != 1 && guess != 2)
{
System.out.println("Invalid entry"); // print incorrect guess entry input
System.out.println("To guess higher enter [1], or to guess lower, enter [2].");
guess = input.nextInt(); //reset scanner "input"
}
//print roll two
System.out.println(); //space
System.out.println("You roll the die again.");
System.out.println("It lands on " + rNum2 + ".");
System.out.println(); //space
if (guess == 1) //guessed higher
{
if (rNum1 == rNum2)
{
System.out.println("Draw!");
}
else if (rNum1 > rNum2)
{
System.out.println("You guessed wrongly.");
}
else
{
System.out.println("You guessed correctly!");
}
}
if (guess == 2) //guessed lower
{
if (rNum1 == rNum2)
{
System.out.println("Draw!");
}
else if (rNum1 > rNum2)
{
System.out.println("You guessed correctly!");
}
else
{
System.out.println("You guessed wrongly.");
}
}
//play again?
System.out.println("Would you like to play again? Enter [y] for yes or [n] for no.");
input.next(); //reset scanner "input"
replay = input.nextLine().toLowerCase();
while((!replay.equals("n") && (!replay.equals("y"))))
{
System.out.println("Invalid entry"); // print incorrect guess entry input
System.out.println("Would you like to play again? Enter [y] for yes or [n] for no.");
replay = input.nextLine().toLowerCase(); //reset scanner "input"
}
if(replay.equals("y"))
{
System.out.println("Restarting game...");
System.out.println(); //space
}
else //(replay.equals("n"))
{
System.out.println("Game over! Thanks for playing!");
}
}
}
Aucun commentaire:
Enregistrer un commentaire