Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm having issues with implementing a would you like to play again and then if the player enters Y then it restarts the whole game. I just need to add another while statement in when I do it just messes it all up.

What I have tried:

package journal.pkg3c;

/**
*
* @author stephenwessels
*/
import java.util.Scanner;
import java.util.Random;
public class Journal3C
{

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random rnd = new Random();

System.out.println("Guess a number between 1 and 10");
int count = 1;
int guess = in.nextInt();
int num = rnd.nextInt(10) + 1;

while(guess != num)
{
System.out.println("Guess a number between 1 and 10");
guess = in.nextInt();
count++;
}
System.out.println("It took " + count + " guesses to guess correctly");
System.out.println("Would you like to play again Y/N?");

}
}
Posted
Updated 1-Feb-18 9:31am

1 solution

You can do it like this:
Java
Boolean play = true;
while (play) {
    // game code here

    System.out.println("Would you like to play again Y/N?");
    play = in.nextLine().trim().equalsIgnoreCase("y"); // "y" will set 'play' to 'true', anything else will set it to 'false'
}
 
Share this answer
 
Comments
Barais_19 3-Feb-18 17:40pm    
It just automatically restarts the game without the user input.
Barais_19 3-Feb-18 17:41pm    
Never mind, just placed it wrong by mistake.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900