eximp
eximp

Reputation: 23

How do i implement a play again feature?

I would like to be prompted when the game finishes; If I would like to play again. And with a Y/N input: either exiting the game or repeat it.

How do I go about this in the most efficient way?

EDIT: Description Resource Path Location Type The method playAgain() is undefined for the type Main Main.java /ScaredyCat/src/se/gruppfisk/scaredycat/main line 12 Java Problem

public boolean playAgain(Scanner keyboard) {
    try {
        System.out.print("Do you want to play again? (Y/N): ");
        String reply = keyboard.nextLine();
        return reply.equalsIgnoreCase("Y");
    } finally {
        keyboard.close();

Upvotes: 2

Views: 3197

Answers (2)

Amber Beriwal
Amber Beriwal

Reputation: 1598

Please note, stream or reader should be closed in the same scope/module, it is created in. In your case, Scanner should not be closed inside playAgain() because, it is an input parameter to the API.

A loop can be implemented to check if user wants to play again or not. Generally do-while loop is used because it will run once before checking the condition. Using other loops will need a variable which is by default true.

Solution using do-while:

boolean playAgain = false;
do{
  Game game = new Game();
  game.play();      
  playAgain = ScaredyCat.playAgain();
}while(playAgain);

Solution using while:

boolean playAgain = true;
while(playAgain){
  Game game = new Game();
  game.play();      
  playAgain = ScaredyCat.playAgain();
}

Add following in ScaredyCat.java

public static boolean playAgain() {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Play again? (Y/N): ");
    String replay = keyboard.nextLine();
    return replay.equals("Y");  //or equalsIgnoreCase
}

The exception you mentioned in edit section means that playAgain() method is not available in your Main.java file. Also, if you are using this method from within main(String[]) method, it must be static and if non-static, it must belong to some object and must be called by object reference. Method suggested by nhouser9 should work.

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

Add a loop to your main method:

public static void main(String[] args) {
    do {
        ScaredyCat game = new ScaredyCat(new Player("Urkel",23),new Player("Steve", 18));
        game.play();
    } while(playAgain());
}

private static boolean playAgain() {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Play again? (Y/N): ");
    String replay = keyboard.nextLine();
    return replay.equals("Y");
}

Upvotes: 2

Related Questions