3

I'm working on the Breakout assignment from the Stanford lectures on iTunes U (still pretty green) and ran into a snarl. I'm trying to set a point value for the different colored bricks so I can calculate a score but my if's don't seem to work. I have a feeling that getColor() isn't returning the value that I think it is; I created a status label to show my what it's returning but I still can't figure out how to test for that. More than likely it's something simple I'm missing or just don't know of yet.

Here's a snippet of the bit I'm working on:

if (collider != null && collider != paddle) {
        remove(scoreLabel);
        vy = -vy;
        Color brickColor = collider.getColor();
        add(new GLabel("" + collider.getColor(), 10, 12));
        double temp = brickVal(brickColor) * scoreMultiplier;
        score += Math.abs(temp);
        addScoreboard();
        remove(collider);
    }
}

private double brickVal(Color c) {
    if (c.equals(Color.RED)) {
        return 10.0;
    } else if (c == Color.ORANGE) {
        return brickVal = 8.0;
    } else if (c == Color.YELLOW) {
        return brickVal = 6.0;
    } else if (c == Color.GREEN) {
        return brickVal = 4.0;
    } else if (Color.CYAN.equals(c)) {
        return brickVal = 2.0;
    } else if (c == Color.MAGENTA) {
        return brickVal = 1.0;
    } else {
        return 1.0;
    }
}

If you need the full code let me know.

Darren Howell
  • 33
  • 1
  • 1
  • 3

1 Answers1

7

Use Color.X.equals(c) for your if cases that are like c == Color.X. You're testing if the objects are the same instance, instead of if they're considered to be equal to each other.

You could also use c.equals(Color.X) like you did for Color.RED, however many people prefer the other way to safeguard against a NullPointerException for cases where c is null.

WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • Thanks. I also found part of my problem was that my scoreMultiplier was 0. *facepalm* – Darren Howell Apr 23 '11 at 00:32
  • And using == as a comparison is legitimate since all color definitions are static. There is no difference in the objects. The equals method merely compares the RGB content of the colors but either should work. – Vetsin Apr 23 '11 at 00:35
  • It's true that `==` will work, as long as the `Color` objects being compared are against the same static instances. If however the `Color` object being compared originated from somewhere else it would be a problem. Likely in this case you're right though and it doesn't matter. It sounds like multiplying by 0 was probably a bigger issue :) – WhiteFang34 Apr 23 '11 at 00:40
  • @Vetsin - this is bad practice for the same reason that it is bad practice to use '==' to compare strings. (It works if you "know" that there is only one instance of each distinct `Color`. But that requires a global invariant ... which tends to make your code fragile, and certainly limits code reuse.) – Stephen C Apr 23 '11 at 00:49