2016-08-22 108 views
-11

這是我的代碼,它給用戶隨機方程來測試他們的知識,並且沒有錯誤出現。當我運行代碼時,它只是不能在Eclipse中編譯。當我執行intelliJ Idea時,它會運行,但沒有代碼出現,我什麼也做不了。如何讓我的java代碼編譯?

package logical; 
import java.util.Random; 
import java.util.Scanner; 

public class logical { 
@SuppressWarnings("resource") 
public static void main (String args[]){ 

    int qn1, qn2; //Numbers for the question 
    int ua; //The users answer 
    int answer; //The actual answer 
    int counter = 0; //Controls the number of questions that can be answered 
    int tally = 0; //Number of correct responses 
    String again = "y"; 
    Scanner in = new Scanner(System.in); 
    Random dice = new Random(); 
    while(again == ("y") || again == ("Y")){ 
    for(counter=1;counter>=5;counter++){ 
    qn1 = 1+dice.nextInt(40); 
    qn2 = 1+dice.nextInt(40); 
    answer = qn1 + qn2; 
     System.out.printf("What is %d + %d",qn1,qn2); 
     ua = in.nextInt(); 
     if(ua == answer){ 
      System.out.println("That is correct!"); 
      counter++; 
      tally++; 
     } 
     else{ 
      System.out.println("Sorry, that is wrong! The correct answer is " + answer); 
     } 
     System.out.println("Would you like to try again?(Y/N)"); 
     again = in.next(); 
     if(again=="y" || again=="Y"){ 
      counter=0; 
     }else { 
      System.out.println("Thanks for playing your results were " + tally + " out of 5"); 
     } 
     } 

    } 
    System.out.println("Thanks for taking the math challenge!"); 
} 
} 
+8

和您的編譯錯誤消息是.....? –

+0

這裏你有邏輯錯誤'again ==(「y」)'你需要使用'equals()'方法比較字符串,而不是'==' –

+3

請刪除花括號上那些醜陋的評論。我不在乎你在大學教過什麼,這使得閱讀更難。 – byxor

回答

0

您的代碼是一個無限循環。
這開始爲真:

while(again == ("y") || again == ("Y")){ 

然後這一點,這是while循環裏面的唯一的事情:

for(counter=1;counter>=5;counter++){ 

立即結束,因爲counter從1開始,且將其期待超過5.

所以如果你運行這個,while循環將永遠循環,無所事事。

  1. 比較字符串與.equals.equalsIgnoreCase,不==

  2. 修復您的for循環。

  3. 正確縮進您的代碼。

0

問題是與for循環

for(counter=1;counter>=5;counter++){...} 

counter=0被初始化。但是,只有在計數器值爲5或大於5時纔會執行循環,因此不會進入循環。但是你在循環內增加了「counter」值。因此,輸出不打印。

0

代碼真正的罪魁禍首是以下幾點: -

String again = "y"; 
     ////////DECLARATION/////////////// 
     Scanner in = new Scanner(System.in); 
     Random dice = new Random(); 
     ////////NOW THE MAGIC HAPPENS///// 
     while(again == ("y") || again == ("Y")){ 
      for(counter=1;counter>=5;counter++){ 

幾點我想提一下:

  1. 布爾條件下while循環從來沒有得到機會來改變。
  2. for循環下的計數器變量總是失敗。
  3. 因此,執行期間繼續希望while和for循環,並陷入永無止境的過程。

我希望這會說清楚。