How to add the “play again?” feature for java

后端 未结 3 1307
生来不讨喜
生来不讨喜 2021-01-24 17:01

Im making a guessing game for my class and I need some help for adding a \"play again\" feature at the end of the game when you\'ve guessed the right number:

pub         


        
相关标签:
3条回答
  • 2021-01-24 17:44

    Just put another while loop over everything.

    boolean playing = true;
    
    while(playing) {
      while(guess != numtoguesses) { // All code }
    
      System.out.println("Do you wish to play again? Y/N");
      String answer = input.nextLine();
      playing = answer.equalsIgnoreCase("y");
      count = 0;
      guess = -1;
    }
    

    Everything together:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        int numtoguesses = rand.nextInt(1000) + 1;
        int counter = 0;
        int guess = -1;
        boolean playing = true;
    
        while(playing) {
    
          while (guess != numtoguesses) {
            System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
            guess = input.nextInt();
            counter = counter + 1;
    
            if (guess == numtoguesses)
                System.out.println ("YOU WIN MOFO!");
            else if (guess < numtoguesses)
                System.out.println ("You're to cold!");
            else if (guess > numtoguesses)
                System.out.println ("You're to hot!");
          }
        }
    
        System.out.println ("It took you " + counter + " guess(es) to get it correct"); 
    
        System.out.println("Do you wish to play again? Y/N");
        String answer = input.nextLine();
        playing = answer.equalsIgnoreCase("y");
        count = 0;
        guess = -1;   
        numtoguesses = rand.nextInt(1000) + 1; 
    } 
    

    You should extract this in a few methods, but I'll leave that up to you.

    0 讨论(0)
  • 2021-01-24 17:58

    There are a lot of options I can think about. The quickest:

    -- place all the code between lines int numtoguesses = rand.nextInt(1000) + 1; (inclusive) and end of main method inside an infinite loop
    -- at the end of your current code block, add an interogation to the user, asking him whether he/she wants to play again (you can define a convention for the pressed keys); this part is placed also inside the infinite loop
    -- if he/she doesn't want to, break the (outer) infinite loop

    0 讨论(0)
  • 2021-01-24 18:02

    One simple approach would be to move the code you've written into a function

       public void play() { 
       ...
       }
    

    and from main do something like:

       do { 
          play();
          playAgain = promptUser;
       } while(playAgain);
    
    0 讨论(0)
提交回复
热议问题