user13049005
user13049005

Reputation:

Trying to make a "Play Again" feature for a game in java

Trying to make a play again feature in a simple math game, at the moment when the user answers 10 questions it will ask the user if they would like to play again Y/N but when you type any response it ends. What do i need to add to make it run the game again when the user types Y (yes)?

public class Main {

    public static void main(String[] args) {
        Question q1 = new Question(5); // to create a new object
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 10; i++) {
            q1.showQuestion2();
            q1.checkAnswer(input.nextInt());
        }

        boolean play = true;
        while (play){
            play = input.nextLine().trim().equalsIgnoreCase("y");
            System.out.println("Would ou like to play again Y/N?");
            String next = input.next();
        }
    }
}

Upvotes: 1

Views: 207

Answers (2)

Angel Koh
Angel Koh

Reputation: 13515

you are very close to the answer already. you just need to

  1. move the question and answer into the loop
  2. check if the variable next is "Y" or not.

if it is not, then set play to false.

boolean play = true;
do {

   Question q1 = new Question(5); // to create a new set of question everytime in the loop.
   Scanner input = new Scanner(System.in);
    for (int i = 0; i < 10; i++) {
        q1.showQuestion2();
        q1.checkAnswer(input.nextInt());

         input.nextLine(); //add this line to "flush" the \n 
    }

    System.out.println("Would ou like to play again Y/N?");  
    //using nextLine() instead of next() -> so that the "/n" in the scanner buffer is cleared.
    String next = input.nextLine().trim() ; //remove spaces 
    play = next.startsWith("y") || next.startsWith("Y");
}while(play);

Upvotes: 1

Arun Gowda
Arun Gowda

Reputation: 3500

You can move the code that has play logic to a new method and call that method while the user inputs Y. This improves code readability

public static void playGame()
{
    //Logic for playing the game goes here
    Question q1 = new Question( 5 ); // to create a new object
    Scanner input = new Scanner( System.in );
    for ( int i = 0; i < 10; i++ ) {
        q1.showQuestion2();
        q1.checkAnswer( input.nextInt() );
    }
}

And alter the main method to conditionally call playGame()

public static void main( String[] args )
{
    boolean continuePlaying = true;
    while ( continuePlaying ) {
        playGame();
        System.out.println( "Would ou like to play again Y/N?" );
        continuePlaying = input.nextLine().trim().equalsIgnoreCase( "y" );
    }
}

Upvotes: 1

Related Questions