This site requires JavaScript, please enable it in your browser!
Greenfoot back
sihaco
sihaco wrote ...

2013/10/27

While loop problem

sihaco sihaco

2013/10/27

#
I have the following while loop, but the game doesn't show, which usually happens when you have an endless while loop. Here's the loop:
public void getCoin() 
    {
        int points = 0;
        while (points < 30){
            if (canSee(Coin.class)){
                eat(Coin.class);
            }
            points = points + 1;
        }
    }
When the Tumbler (Batman car) touches a coin, it should eat it and the field points should be increased with one. Why doesn't this loop work? The condition is that as long as you don't have 30 points, the Tumbler should collect coins and with every collected coin, the points should increase with one. How can I change this code to make it work?
SPower SPower

2013/10/27

#
You re-create your points variable every time you execute the loop, so it will always end up 30, but you won't be able to use it. (and also you don't show the code where you show it). This should work:
// in the class where getCoin is
private int points = 0;

public void getCoin()
{
    while (points < 30) {
        if (canSee(Coin.class)) {
            eat(Coin.class);
        } else {
            break; // don't touch a coin, so stop the loop
        }
        points += 1; // add 1
}
and display the points instance variable.
erdelf erdelf

2013/10/27

#
this should work
    public void getCoin()   
        {  
            int points = 0;  
            while (points < 30){  
                if (canSee(Coin.class)){  
                    eat(Coin.class);  
                    points = points + 1;  
                }  
            }  
        }  
in ur code the points are increasing every cycle
SPower SPower

2013/10/27

#
But that only happens when you eat a Coin instance, otherwise the loop would break :)
sihaco sihaco

2013/10/27

#
Okay thanks guys, it works!
You need to login to post a reply.