i find it difficult to interpret an if statement inside a while loop body. The code i am trying to understand is:
public int findFirst(String searchString)
{
int index = 0;
// Record that we will be searching until a match is found.
boolean searching = true;
while(searching && index < files.size()) {
String filename = files.get(index);
if(filename.contains(searchString)) {
// A match. We can stop searching.
searching = false;
}
else {
// Move on.
index ;
}
}
if(searching) {
// We didn't find it.
return -1;
}
else {
// Return where it was found.
return index;
}
}
Can someone please explain how i shall interpret that method ? All the help that i can get is much appreciated !
CodePudding user response:
Once we find your searchString in the filename, the boolean is set to false so you do not enter in the while() loop next time and enter in your else() case which return the index.
Instead of using a boolean, you could use the break keyword in order to leave the while loop
int index=-1, i=0;
while(i < files.size()) {
if(file.get(i).contains(searchString)){
index = i;
break;
}
i ;
}
return index;
Maybe it's more readable since there is less if-else statement ?
CodePudding user response:
The if statement in the while loop checks whether the string corresponds with the filename. if so, the while loop stops iterating itself more but goes till the end of the current cycle(but there is nothing to be done, I am telling you this just in case). But if the string does not correspond to filename, loop goes on until the filename you are looking after(using searchString) is found or all the files are checked and the filename you were looking after was not found.