2017-02-14 42 views
0

我在下面的代碼中的目標是不斷猜測,直到用戶猜測到正確的數字或​​退出。要退出,我可以很容易地打破我的循環,但是當我嘗試繼續循環時,它無法正常工作。首先它需要多個輸入,然後也完全重新生成我的號碼,而我想要做的是不斷猜測(詢問用戶)相同的隨機數。 下面是我的代碼:無法通過while循環成功重新循環

public class Test { 
public static void main(String[] args) { 
    int count, randNum, guess; 
    count = 0; 
    Scanner scan = new Scanner(System.in); 

    while (true) { 
     Random rand = new Random(); 
     randNum = rand.nextInt(100) + 1; 
     System.out.println("Guess a number b/w 1 and 100"); 
     guess = scan.nextInt(); 
     count += 1; 

     if (guess == randNum) { 
      System.out.println("Correct guess."); 
      System.out.println("It took " + count + " tries to guess the right number"); 
      System.out.println("Would you like to play again? "); 
      System.out.println("Press any letter to play again or q to quit: "); 
      if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') { 
       break; 
      } 
      else{ 
       continue; 
      } 
     } 
     if (guess > randNum) { 
      System.out.println("Your guess is bigger than actual number. Would you like to try again?"); 
      System.out.println("Press q to quit or any other letter to try again"); 
      if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') { 
       break; 
      } 
      else { 
       continue; 
      } 
     } 
     else if (guess < randNum) { 
      System.out.println("Your guess is smaller than actual number. Would you like to try again?"); 
      System.out.println("Press q to quit or any other letter to try again"); 
      if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') { 
       break; 
      } 
      else { 
        continue; 
       } 
      } 

     } 

} 

}

+1

談論一個移動的目標 - randNum正在對環路 –

+0

您需要的遊戲和嘗試分成外部/內部循環的每一次迭代中重新設置。 – shmosel

回答

1

生成隨機數應該是while語句之前的代碼。當您撥打continue時,它會返回到while塊的第一行,並因此生成另一個隨機數。

+0

感謝您的幫助。它確實解決了這個問題,但現在還有一個問題。當我輸入一個字母以繼續時,我必須在循環重新開始前輸入約3次。我不明白這是爲什麼 –

1

你的聲明,宣佈對INT randNum是while循環裏面,所以每次while循環重複的時間,數量聲明(再一次),如果你想設置爲1和100

之間的值。防止這種情況,聲明變量並用while循環外的隨機值初始化它。

一個小方面的說明:通過初始化while循環內部的變量,您將其範圍限制得比您想要的要多。每次循環時,您創建的前一個randNum不再存在,然後創建一個新的randNum。基本上,如果你想讓它更永久,在循環之外初始化它。

此外,如果您只希望第一次請求1到100之間的數字,請將其移到循環之外。然而,這取決於你是否希望每次都問,或者只是一次。

//… 
public static void main(String[] args) { 
    int count, randNum, guess; 
    count = 0; 
    Scanner scan = new Scanner(System.in); 
    Random rand = new Random(); 
    randNum = rand.nextInt(100) + 1; 
    System.out.println("Guess a number b/w 1 and 100");    
    while (true) { 
     /*Random rand = new Random(); 
     randNum = rand.nextInt(100) + 1; 
     System.out.println("Guess a number b/w 1 and 100");*/ 

     guess = scan.nextInt(); 
     count += 1; 
     //…