2015-01-06 24 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之内吗?