Can someone explain this to me? First of all, I know why this code
String getName(){
for(;;){}
}
will violate a return
type method: it's infinite, but why does this code need a final return value?
String getName(){
for(;i < limit; i++){// i is already defined
if(someArrayList.get(i).isDead)
continue;
return someArrayList.get(i).name;
}
//needs a final return
}
The return value exists inside the loop and returns the value for the getName()
method, so what is the reason? another post suggested that what if the loop is negative for my condition, so I rewrote it this way:
String getName(){
for(; i < 10; i++){// i is already defined
if((i+1) == limit){
if(!someArrayList.get(i).isDead)
return "";
}else{
if(someArrayList.get(i).isDead)
continue;
return someArrayList.get(i).name;
}
}
// needs a final return
}
The same compile time error, even if I re-define i
in the for loop condition, to 0
, so my i
becomes zero and if the inner condition checks out negative I handle it myself. All in all, if I nest it in an infinite loop, it's ok.
String getName(){
for(;;){
for(; i < limit; i++){// i is already defined
if(someArrayList.get(i).isDead)
continue;
return someArrayList.get(i).name;
}
}
}
Is it because it has a range? Because I feel it covers all scenarios, I just want to know why, before I add the last return
and life's good
And lastly this works alright:
String getName(){
for(;;){
for(; i < limit; i++){// i is already defined
if(someArrayList.get(i).isDead)
continue;
return someArrayList.get(i).name;
}
return "";
}
}