2013-03-18 98 views
0

我有這個我爲課程創建的java代碼。我已經嘗試並繼續失敗實施一個突破聲明。試圖設置break語句

有人能指出我正確的方向嗎?

import java.util.Scanner; 

public class gradeAverage { 

    public static void main(String[] args){ 
      Scanner input = new Scanner(System.in); 
      int input1; 
      int input2; 
      int input3; 

      //Calculate 
      int studentAvg; 

      //Prompt for first user input or break if input = q 
      System.out.print("Enter first student grade or q to quit: "); 
      if { 
       (input1=input.nextInt() = q) 
       break; 
       else 
        input1=input.nextInt() =; 
    } 
      //Prompt for second user input or break if input = q 
      System.out.print("Enter second student grade or q to quit: "); 
      input2=input.nextInt(); 

      //Prompt for third user input or break if input = q 
      System.out.print("Enter third student grade or q to quit: "); 
      input3=input.nextInt(); 

      studentAvg=(input1+input2+input3)/3; 

      System.out.printf("The Student's grade average is %d\n" , studentAvg); 

    } 
} 
+0

請勿將變量遠離真正需要使用它的地方。 'int input2 = input.nextInt();''int input3 = input.nextInt();''int studentAvg =(input1 + input2 + input3)/ 3;''''代碼找出這個特定的'studentAvg'是int/lond/float還是double ... – dantuch 2013-03-18 02:09:00

回答

5

break語句需要一個循環或某種(forwhile,或do),你無法擺脫的if條件內。

如果你把你的代碼,這裏面:

while(true) { 
    ... 
} 

那麼你的突破將正常工作。

另外一個if語句的格式爲:

if (condition) { 
    ... 
} else { 

} 

你似乎在你的代碼if { (condition) ...

哦,=是一個值的一個變量賦值,==是平等檢查,你讓他們混淆起來。

+1

他/她還得修正他/她的if語句的整個語法。 – 2013-03-18 02:02:05

+2

我認爲'return'會比添加'while(true)'讓'break'打破某些東西更合適... – dantuch 2013-03-18 02:02:55

+1

和'something = something2'不是條件:) – dantuch 2013-03-18 02:04:49

-2

//假設輸入是掃描儀對象。

System.out.print("Enter first student grade or q to quit: "); 
      if ((input1=input.nextline()).equalsIgnoreCase("q")) //do you want to use == or =? 
       break; 

       else{ 
        //do something 
    } 

這應該對你有用。乾杯。

+0

打破什麼?無論如何 - 我敢打賭它不會編譯;) – dantuch 2013-03-18 02:06:01

+0

這不會編譯。 'else'之前沒有括號。 – fireshadow52 2013-03-18 02:06:21

+0

它只有一個片段,並且在else之前不需要括號。 if是隱式完成的,因爲它下面只有一條語句。 雖然我不確定要檢查什麼條件。唯一的問題是,由於大括號錯位,較早的代碼不起作用。 – user2180705 2013-03-18 02:11:56

0

首先你的If語句的語法是完全錯誤的。這需要糾正。

其次,Break語句用於打破之間的循環。所以它應該像

,而{ ................ 休息; ................

}

對於(.........){

分段; ........ }