Boolean in FOR loop

17,437

Solution 1

Here "Boolean" is using to terminate the loop as soon as the inputted "id" found in your array. The good thing is the compiler don't have to search until last index wheres "id" already found.

Solution 2

The conditional statement inside the for loop reads

i < z && !found

When 'found' is true, the for loop will stop looping. You can read more about for loops here

For loop syntax looks like this:

for (initialize ; condition ; increment) {}

It's also possible to replace your for loop with a while loop.

int i = 0;
int found = false;
while(i < z && !found) {
    if(arr[i].getId()==id){
        found = true;
        index = i;
    }
}

In both cases, you can simplify your conditional using the "break" keyword. The break keyword causes a loop to exit immediately. This may or may not be the appropriate solution here, but it does show another way to handle these kinds of loops.

for(int i=0; i<z; i++){
    if(arr[i].getId()==id){
        index = i;
        break;
    }   
} 
Share:
17,437
topacoBoy
Author by

topacoBoy

Updated on June 04, 2022

Comments

  • topacoBoy
    topacoBoy almost 2 years

    I don't understand this code. One of my friend thought me to use the boolean to make it work. I don't really understand when he explains it. Why is the found in the for loop?

    int id = input.nextInt();   
    boolean found = false;
    for (int i = 0; i < z && !found; i++){
        if (arr[i].getId() == id){
            found = true;
            index = i;
        }   
    }