2016-03-15 16 views
0

猜測嘗試提示用戶再次玩遊戲的遊戲。當我提示用戶再次玩遊戲後,遊戲回到它之前的隨機數而不是重新啓動

我將它設置爲一個while循環,但由於某種原因,它仍然使用前一個遊戲的相同數量。這是爲什麼?我是否必須在while循環中添加更多細節?

public class Guessing_zulueta { 


public static int getOneInt() { 
    //we will get one integer from the keyboard 
    Scanner in = new Scanner(System.in); 
    System.out.printf("Enter an integer: "); 
    return in.nextInt(); 
} 


public static int random = getRand(); 

public static final int MAX = 100; 


public static int getRand() { 

    Random randGenerator = new Random(); 
    int x = randGenerator.nextInt(MAX); 

    return x; 

} 

public static void main(String[] args) {//here is my problem 
    while (true){ 
     guessingGame(); 
    System.out.println("Do you wish to play again? (1 for yes, -1 for no: "); 
    Scanner scan2 = new Scanner(System.in); 
    int val = scan2.nextInt(); 
    if (val == 1) 
     guessingGame(); 
    if (val == -1) 
     break; 
    } 

} 

public static void guessingGame() { 

     int input = getOneInt(); 

     if (input == random) { 
      System.out.println("Congratulations"); 
     } 

     if (input > random) { 
      System.out.println("Too big."); 
      guessingGame(); 
     } 
     if (input < random) { 
      System.out.println("Too small."); 
      guessingGame(); 
     } 
} 
} 

回答

0

當您加載類時,您只需指定random的值。要在每次玩遊戲時分配一個新的隨機數,您需要在撥打guessingGame之前分配它。

我也稍微修改了你的循環;如果用戶輸入1,然後在循環開始時再次調用,則以前調用的是guessingGame()。現在如果用戶輸入1(或者除-1之外的任何值),它只會調用一次。

public static void main(String[] args) { 
    while (true) { 
     random = getRand(); 
     guessingGame(); 

     System.out.println("Do you wish to play again? (1 for yes, -1 for no: "); 
     Scanner scan2 = new Scanner(System.in); 
     int val = scan2.nextInt(); 
     if (val == -1) { 
      break; 
     } else { 
      // Any other value will continue to loop and play another game. 
     } 
    } 
} 
+0

這樣做是爲了在每次遊戲後而不是每場遊戲後隨機化數字 –

+0

對不起,我最初誤讀了您的代碼。我已經更新了我的答案。 – DanielGibbs