如何添加“再玩一次?” java的功能

时间:2013-11-26 22:03:42

标签: java

我正在为我的班级制作一个猜谜游戏,当你猜到正确的数字时,我需要一些帮助来在游戏结束时添加“再次播放”功能:

public class GuessingGame
{   
    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;

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

3 个答案:

答案 0 :(得分:1)

一种简单的方法是将您编写的代码移到函数中

   public void play() { 
   ...
   }

并从main执行以下操作:

   do { 
      play();
      playAgain = promptUser;
   } while(playAgain);

答案 1 :(得分:0)

在所有事情上放一个while循环。

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

一切都在一起:

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

你应该用几种方法提取这些,但我会把它留给你。

答案 2 :(得分:0)

我可以考虑很多选择。最快的:

- 将所有代码放在行int numtoguesses = rand.nextInt(1000) + 1;(包括)之间,将主方法结束放在无限循环中 - 在当前代码块的末尾,向用户添加一个interogation,询问他/她是否想再次播放(您可以为按下的键定义约定);这部分也放在无限循环内 - 如果他/她不想,打破(外部)无限循环