java 测试颜色是否相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5761117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing if colors equal
提问by Darren Howell
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.
我正在 iTunes U 上的斯坦福讲座中完成 Breakout 作业(仍然很绿色),但遇到了咆哮。我正在尝试为不同颜色的积木设置一个点值,以便我可以计算分数,但我的 if 似乎不起作用。我有一种感觉, getColor() 没有返回我认为的值;我创建了一个状态标签来显示它返回的内容,但我仍然不知道如何进行测试。很可能这是我遗漏或只是不知道的一些简单的东西。
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.
如果您需要完整代码,请告诉我。
回答by WhiteFang34
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.
使用Color.X.equals(c)
您的情况,如果是喜欢c == Color.X
。您正在测试对象是否是同一个实例,而不是它们是否被认为彼此相等。
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
.
您也可以c.equals(Color.X)
像 for 那样使用Color.RED
,但是许多人更喜欢用另一种方式来防止NullPointerException
for 情况 where c
is null
。