2016-01-21 41 views
1

我用三次嘗試創建了這個簡單的猜謎遊戲,但我需要幫助添加代碼,以便它可以顯示「首次猜測」,後面跟着用戶放入的整數,「第二次猜測」 ,等等...我現在只是「輸入你的猜測」,這是第一次嘗試。我需要做什麼?我很困惑如何去做這件事。對不起,如果問題很混亂。簡單的猜謎遊戲。 「你的第一個猜測是......」

import java.util.Scanner; 

public class guess { 

public static void main(String[] args) { 

    int randomN = (int) (Math.random() * 10) + 1; 

    Scanner input = new Scanner(System.in); 
    int guess; 
    System.out.println("Enter a number between 1 and 10."); 
    System.out.println(); 
    int attempts = 0; 

    do { 
     attempts++; 

     System.out.print("Enter your guess: "); 
     guess = input.nextInt(); 

     if (guess == randomN) { 
      System.out.println("You won!"); 
     } else if (guess < 1 || guess > 10) { 
      System.out.println("out of range"); 
      attempts = +1; 
     } else if (guess > randomN) { 
      System.out.println("Too high"); 
     } else if (guess < randomN) { 
      System.out.println("Too low"); 
     } 

    } while (guess != randomN && attempts < 3); 

    if (guess != randomN && attempts == 3) { 
     System.out.println("Number is " + randomN); 
    } 


    } 

} 
+1

'嘗試= + 1'也許應該嘗試'+ = 1'或者只是嘗試''++。 – user1803551

+0

'我需要幫助添加代碼'在哪個部分?用戶輸入密碼後?你想輸出用戶輸入?還是在運行結束? – user1803551

+0

將所有答案存儲在一個ArrayList中(''列表 guesses = new ArrayList ();'')並在while循環結束後將其打印出來 – mmuzahid

回答

0

你可以外main創建另一個靜態方法,可以輸出取決於attempts的自定義消息在哪裏。

public static String describe(int attempts) { 
    switch(attempts) { 
     case 1: return "First guess: "; 
     case 2: return "Second guess: "; 
     case 3: return "Third guess: "; 
     default: return "Enter your guess: "; //should not happen 
    } 
} 

然後在你main使用它像這樣:

... 
do { 
    attempts++; 

    System.out.print(describe(attempts)); 
... 
}