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

2012/6/24

getting integers

gusbus123 gusbus123

2012/6/24

#
how would u go about in an easy way of getting integers from different classes? i have a score int in each of my 5 ghost classes and i want to find the total of all 5 int's as its own integer in the player class. Right now i have something like this in the player class but it cannot find the variables in the for loops...
private Ghost addScores()
    {
        for (Object obj : getWorld().getObjects(Ghost1.class)) {
            Ghost1 a = (Ghost1) obj;
            int ga = a.playerScore;
        }
        for (Object obj : getWorld().getObjects(Ghost2.class)) {
            Ghost2 b = (Ghost2) obj;
            int gb = b.playerScore;
        }
        for (Object obj : getWorld().getObjects(Ghost3.class)) {
            Ghost3 c = (Ghost3) obj;
            int gc = c.playerScore;
        }
        for (Object obj : getWorld().getObjects(Ghost4.class)) {
            Ghost4 d = (Ghost4) obj;
            int gd = d.playerScore;
        }
        for (Object obj : getWorld().getObjects(Ghost5.class)) {
            Ghost5 e = (Ghost5) obj;
            int ge = e.playerScore;
        }
        ghostScores=ga.playerScore+gb.playerScore+gc.playerScore+gd.playerScore+ge.playerScore;
        return null;
    }
the code doesnt have to be in this format, i just tried this cause i thought it would work. I just need something that works with getting the playerScore's into one int.
danpost danpost

2012/6/24

#
Try this:
private void addScores()
{
    int gSum = 0;
    for (Object obj : getWorld().getObjects(Ghost1.class)) {
        Ghost1 a = (Ghost1) obj;
        gSum += a.playerScore;
    }
    for (Object obj : getWorld().getObjects(Ghost2.class)) {
        Ghost2 b = (Ghost2) obj;
        gSum += b.playerScore;
    }
    for (Object obj : getWorld().getObjects(Ghost3.class)) {
        Ghost3 c = (Ghost3) obj;
        gSum += c.playerScore;
    }
    for (Object obj : getWorld().getObjects(Ghost4.class)) {
        Ghost4 d = (Ghost4) obj;
        gSum += d.playerScore;
    }
    for (Object obj : getWorld().getObjects(Ghost5.class)) {
        Ghost5 e = (Ghost5) obj;
        gSum += e.playerScore;
    }
    ghostScores = gSum;
}
and make sure that the 'playerScore' variables in all of the classes are 'public' (not 'private'). Either that, or create a 'public' method in each class that returns the value of 'playerScore' in it, and call them in the code above, instead of trying to access the values directly.
gusbus123 gusbus123

2012/6/24

#
k ill try that. Edit: yep it works. Thx.
You need to login to post a reply.