2014-10-02 63 views
0

代碼顯示沒有錯誤的編譯器,但是當代碼運行和循環符合要求保持它打印出在這裏不停消息的畫面http://i62.tinypic.com/23if4uv.png如何修復while循環的運行時錯誤?

也在這裏是我使用的代碼:

Scanner keyb = new Scanner(System.in); 
int numbg = (int) (100*Math.random())+1; 
String one = "That was lucky!"; 
String twofour="That was amazing!"; 
String fivesix= "That was good."; 
String seven= "That was okay"; 
String enine = "That was not versy good"; 
String tm= "That just insn't your game"; 
System.out.println("Enter a guess between 1 and 100: "); 
int numbu = keyb.nextInt(); 
int wrong = 0; 
while (numbg != numbu) { 
    if (numbu < numbg) { 
     System.out.println("Your guess too low. Try again. "); 
     wrong++; 
     System.out.println("Enter a guess between 1 and 100: "); 
     numbu=keyb.nextInt(); 
    } 
    else if (numbu > numbg && numbu <= 100) { 
     System.out.println("Your guess too high. Try again."); 
     wrong++; 
     System.out.println("Enter a guess between 1 and 100: "); 
     numbu=keyb.nextInt(); 
    } 
    else if (numbu > 100) { 
     System.out.println("Your guess is out of range. Pick a number betwen 1 and 100"); 
     numbu=keyb.nextInt(); 
    } 
    while (numbg == numbu) { 
     if (wrong >= 1) { 
      System.out.println(one); 
     } 
     else if (wrong >= 2 && wrong <= 4) { 
      System.out.println(twofour); 
     } 
     else if (wrong >= 5 && wrong <= 6){ 
      System.out.println(fivesix); 
     } 
     else if (wrong == 7) { 
      System.out.println(seven); 
     } 
     else if (wrong >=8 && wrong <= 9){ 
      System.out.println(enine); 
     } 
     else if (wrong >= 10) { 
      System.out.println(tm); 
     } 
    } 
} 
+2

我會建議使用調試器來解決這個問題 – PsyCode 2014-10-02 22:39:08

+5

一旦你進入'while(numbg == numbu)'循環,你永遠不會離開它,因爲'numbg'和'numbu'都不會改變。所以難怪循環沒有終止。嘗試設置'numbg = 0; numbu = 1'在循環範圍的末尾,然後檢查你是否仍然有同樣的問題。 – hoefling 2014-10-02 22:41:11

+0

@ Mr.Yetti現在感謝我修改了刪除操作,並從分支 – Joscoth 2014-10-03 01:04:30

回答

0

您所擁有的while循環將永遠不會終止,因爲總會滿足要求。我建議只使用一個if語句,這樣它只會檢查一次,如果符合要求,它只會說一次字符串。另外,您應該更改while循環中應該更改爲(錯誤的< = number)而非> =的所有if和if else語句,因爲該條件將始終爲true,因爲這意味着如果您使用了數字或更多猜測找到它而不是那個數字或更少。

+0

開始......並修復了第一條if語句。 – spudone 2014-10-02 22:46:35

+0

@spudone如果陳述不正確? – PsyCode 2014-10-02 22:51:09

+1

如果(錯誤> = 1)在任何其他條件之前總是成立。 – spudone 2014-10-02 22:53:24