2013-08-04 23 views
0

显然我在这里缺少一些基本的东西。我有一个函数,在各种if语句中遍历函数的返回语句。这样做的好处显而易见,但我遇到了我不熟悉的情况。如果语句返回值没有在Android中返回

我跟着执行我的程序通过断点,并发现它正常进行返回语句。但是,在到达该语句之后,它跳过该函数的其余部分并转到函数底部的return语句并返回坐在那里的值。下面是代码片段,它是数百行的长,所以我不想张贴整个事情,只是部分我追查通过:

public Location getBestLocation(Context c){ //the header 

else if(gps_enabled && passive_enabled && !network_enabled){ 
     if(hGPSLast != null && hPassive != null){ 
      if(hGPSLast.getTime() > hPassive.getTime() && System.currentTimeMillis() - hGPSLast.getTime() < 300000){ 
       return hGPSLast; 
      }else if(hPassive.getTime() > hGPSLast.getTime() && System.currentTimeMillis() - hPassive.getTime() < 300000){ 
       return hPassive; 
      }else{ 
       hGPSBest = getGPSloc(c); 
       if(hGPSBest.getTime() == hGPSLast.getTime()){ 
        if(hPassive.getTime() > hGPSLast.getTime()){ 
         return hPassive; 
        }else{ 
         return hGPSLast; 
        } 
       }else{ 
        return hGPSBest; 
       } 
      } 
     }else if(hGPSLast != null && hPassive == null){ 
      if(System.currentTimeMillis() - hGPSLast.getTime() <300000){ 
       return hGPSLast; 
      }else{ 
       hGPSBest = getGPSloc(c); 
       return hGPSBest; 
      } 
     }else if(hPassive != null && hGPSLast == null){ 
      if(System.currentTimeMillis() - hPassive.getTime() < 300000){ 
       return hPassive; 
      }else{ 
       hGPSBest = getGPSloc(c); 
       if(hGPSBest != null){ 
        return hGPSBest; 
       }else{ 
        return hPassive; 
       } 
      } 
     } 

回报的一个在身体的那部分达到了,但是那么代码跳转到最底部,我有这样的:

Criteria criteria = new Criteria(); 
    String best = lm.getBestProvider(criteria, true); 
    //since you are using true as the second parameter, you will only get the best of providers which are enabled. 
    def = lm.getLastKnownLocation(best); 
    return def; 

的代码返回“高清”,我定义为我本来希望将通过代码来填补空白的持有人位置的对象只是如果出于某种原因,身体上没有任何回报达到它的上方。我在这里错过了什么?

+5

Ouch,所有那些嵌套的if-else的代码尖叫重构。 – Booger

+3

'return'退出方法 - 总是。您的调试器正在玩弄你的神经,或者你误解了它的结果。 – assylias

+0

@assylias我认为你是对的。我在我的代码中进行了更正,在我开始搜索新值之前先指定了最后知道的值,并返回最后一个已知值。我认为这是一个问题,我的请求更新的位置是在一个不同的线程中完成的,并且在调用线程询问值时尚未完成。 – user2097211

回答

4

A return命令立即忽略所有剩余的方法代码并退出当前的方法。它将立即返回到调用方法本身的前一个函数。

例如:

if(hPassive.getTime() > hGPSLast.getTime()){ 
    return hPassive; 
}else{ 
    return hGPSLast; 
} 

可以改写为

if(hPassive.getTime() > hGPSLast.getTime()){ 
    return hPassive; 
} 

return hGPSLast; 

的方法将总是返回二者中的任何,并且跳过后续的代码。

+2

除非当然有'try ... finally'块,那么所有的投注都关闭。 – Martin

+0

可以改写为:'return hPassive.getTime()> hGPSLast.getTime()? hPassive:hGPSLast;' –