Destroyer2super
Destroyer2super

Reputation: 45

How do i add an play again option to this java code?

the notepad++ file screenshot

is there a way to declare a char early on but use it only later, because when i try to declare it as 0 early on then it will just cause an error because the answer of while is supposed to be 'Y'. i could get it to loop and play again by asking the question before playing but I only want it to ask the option to play again at the end of the game. would appreciate it if anyone could tell me how to get this to work, thank you.

public class soodsami_a3 {

    public static void main(String[] args) {
        Scanner sam = new Scanner(System.in);
        // Random number generator
        int Randomizer = (int)(Math.random() * 100) + 1;

        while (playagain == 'y') {
            System.out.println("I'm thinking of a number between 1 and 100");
            System.out.println("What is it?");
            System.out.print("Guess:  ");
            int Useranswer = sam.nextInt();
            
            while (Useranswer != Randomizer) {
                if (Useranswer < Randomizer) {
                    System.out.println("Too low.");
                    System.out.print("Guess:  ");
                    Useranswer = sam.nextInt();
                } else if (Useranswer > Randomizer) {
                    System.out.println("Too high.");
                    System.out.print("Guess:  ");
                    Useranswer = sam.nextInt();
                }
            
                if (Useranswer == Randomizer) {
                    System.out.println("You got it!");
                }
            
                System.out.print("would you like to play again (Y/N) ");
                char playagain = sam.next().toUpperCase().charAt(0);
            }
        }
        
        System.out.println("Thanks for playing");
    }
}

Upvotes: 3

Views: 503

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

public static void main(String[] args) {
    // ...
    char playagain = 'y';

    while (playagain == 'y') {
        // ...
        playagain = scan.next().toLowerCase().charAt(0);
    }

    System.out.println("Thanks for playing");
}

Upvotes: 2

Dropout
Dropout

Reputation: 13866

It would be a better practice to have playagain as a boolean and have it set to false on initialization. Then use a do-while cycle, to have the condition evaluated at the end of the cycle, so that it runs at least once

boolean playAgain = false;
do {
    System.out.println("I'm thinking of a number between 1 and 100");
    //..other code..
    playAgain = sam.next().toUpperCase().charAt(0) == 'Y';
} while (playAgain);

Upvotes: 1

Related Questions