2013-11-26 69 views
0

林作出猜謎遊戲我的課,我需要在比賽的末尾添加一個「重新播放」功能,當你已經猜到正確數量的一些幫助:如何添加「再次播放?」功能對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");  
    } 
} 
+0

將遊戲邏輯本身封閉在循環中? – admdrew

回答

0

只要把另一個同時循環一切。

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

你應該在幾個方法提取這一點,但我會離開,給你。

1

一個簡單的方法是將移動你寫成函數的代碼

public void play() { 
    ... 
    } 

main做這樣的事情:

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

有很多的選擇,我能想到關於。最快:

- 全部到位線之間的代碼int numtoguesses = rand.nextInt(1000) + 1;(含)和一個無限循環
內主要方法結束 - 在當前的代碼塊的結束,一個刑訊添加到用戶,要求他無論他/她想再次玩(你可以爲按下的鍵定義一個約定);這部分也放置在無限循環內
- 如果他/她不想要,打破(外部)無限循環