jiji jiji - 2 months ago 7
Java Question

Return an element of a for-loop outside the for-loop

How can I do to return an element of a for-loop?

private List<String> list = new ArrayList<String>();
//we only neeed one good element of the list
String find(){
for (int i=0; i<list.size(); i++){
if (list.get(i).isGood()) {
return list.get(i);
}
}
return list.get(i); //doesn't work obviously, but how to make it work?
}


It doesn't compile because there is no return statement. I would like to return list.get(i).

Answer

Calling break after a return call is unnecessary, since the method is exited after the return statement. Therefore the break statement has no chance of ever being executed which is why this code doesn't compile.

Furthermore you need a return or throw statement after the loop in case no value is returned form the loop, e.g.:

String find(){
   for (int i=0; i<list.size(); i++){
        if (list.get(i).isGood()) {
            return list.get(i);
        }
    }
    return null;
}
Comments