user2973447
user2973447

Reputation: 381

How would I convert this code into a loop?

public Bee anotherDay(){
    flower = garden.findFlower();
    int pol = 5;
    bool=flower.extractPollen(pol);
    if(bool=true){  
        hive.addPollen(pol);
    }else{
        ++pol;
        bool=flower.extractPollen(pol);

        if(bool=true){  
            hive.addPollen(pol);
        }else{
            ++pol; //etc.
        } 
    }

The point of that code is to:

1)use the findFlower() method on garden ot return a flower
2)use the extract pollen method on the flower with 5 as the initial paramater
3)If there isn't 5 pollen in the flower, the method returns false so try again with 4
4)If there isn't 4 try with 3 etc. until 0. 

I was thinking of using a for loop but I do not know how to break out of it if the method was successful and returned true, so I don't keep going to get 5+4+3+2+1 pollen from the flower.

Upvotes: 0

Views: 86

Answers (1)

flower = garden.findFlower();
for(int pol=5; pol>0; pol--)
{
    if(flower.extractPollen(pol) {
        hive.addPollen(pol);
        break;
    }
}

Upvotes: 5

Related Questions