How do i implement a play again feature?

拥有回忆 提交于 2019-12-13 16:02:12

问题


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();

回答1:


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");
}



回答2:


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.



来源:https://stackoverflow.com/questions/39822820/how-do-i-implement-a-play-again-feature

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!