2015-01-06 25 views
-3

到目前爲止的代碼:想不通這是爲什麼死代碼

@Override 
public Double getNotaMedia() { 
    Double notaAux = 0.0; 
    int aux1 = this.notas.size(); 
    int aux3 = 0; 

    if(!this.notas.isEmpty()){ 
     for (int aux2 = 0; aux2 <= aux1; aux2++){ 
      if(this.notas.get(aux2).getValorNota() >= 5.0){ 
       notaAux += this.notas.get(aux2).getValorNota(); 
       aux3 = aux3 + 1; 
      } 
      return notaAux.doubleValue()/aux3; 
     } 
    } 
    return notaAux; 
} 

根據月食aux2++是死代碼,我想不通爲什麼。

+3

不幸的是,像你一樣編輯你的問題,使代碼正確,破壞問題的原因。現在,如果有人後來回來看這個問題,他們在試圖弄清楚發生了什麼時會遇到很多問題。 StackOverflow的設計使問題和答案可能對以後研究自己問題的人有用。我打算要求你把它恢復原樣,但是阿沙哈已經這樣做了。 – ajb

回答

6

你必須在你for -loop身體的末端return語句,因此增量aux2++將永遠不會被執行,因爲該功能將在未來循環迭代開始前返回(或者更具體地說,之前的第一個完全結束)。在每次循環迭代完成後

+0

對,返回需要在另外兩個括號之間!謝謝。 –

0
for (int aux2 = 0; aux2 <= aux1; aux2++){ 
     if(this.notas.get(aux2).getValorNota() >= 5.0){ 
      notaAux += this.notas.get(aux2).getValorNota(); 
      aux3 = aux3 + 1; 
     } 
     return notaAux.doubleValue()/aux3; 
    } 

在這種for聲明,aux2++將被執行。但是在這段代碼中,循環的第一次迭代(如果有的話)以return結尾,這會突然完成循環(以及整個方法)。因此,該程序無法達到aux2++表達式。

return應該在if之內嗎?