颜色等于另一种颜色,Java
好的,我在变量C中设置的颜色等于coal1中的变量,但是当通过if语句时,返回的结果是它们不相等。我已经用打印行调试过了,结果对我来说很奇怪。任何帮助都将不胜感激 代码 当我运行它时,我得到颜色等于另一种颜色,Java,java,colors,equals,Java,Colors,Equals,好的,我在变量C中设置的颜色等于coal1中的变量,但是当通过if语句时,返回的结果是它们不相等。我已经用打印行调试过了,结果对我来说很奇怪。任何帮助都将不胜感激 代码 当我运行它时,我得到 c before the if: java.awt.Color[r=225,g=225,b=225] coal 1 before the if: java.awt.Color[r=255,g=255,b=255] c after the if: java.awt.Color[r=225,g=225,b=22
c before the if: java.awt.Color[r=225,g=225,b=225]
coal 1 before the if: java.awt.Color[r=255,g=255,b=255]
c after the if: java.awt.Color[r=225,g=225,b=225]
coal1 after the if: java.awt.Color[r=255,g=255,b=255]
color changed
尝试使用instanceof操作符。以下是我提出的解决方案:
int R = 255;
int G = 255;
int B = 255;
if ((c.getRed() == R) && (c.getGreen() == G) && (c.getBlue() == B)) {
System.out.println("Found color");
} else {
System.out.println("Couldnt find color");
}
根据您的输出,它们是不一样的
c的红色、绿色和蓝色组件为225,而coal1的组件为255
Color.equals(Color o)
比较RGB值,在您的情况下,RGB值不相同我不太清楚Java,但我怀疑c.equals(foo)
只有在c
和foo
是同一个对象时才会返回true,这不是您想要的。您想知道c
和foo
是否具有相同的值集。它们。。。他们不平等<代码>255
!=225
,@DanPichelman-这是完全错误的(你把它倒过来,=
比较参考值)@BrianRoach-你的眼睛比我好。我完全错过了。伟大的呼唤;我的错。你最初发布的代码没有任何问题,它产生了正确的结果。为什么???为了什么目的?因为它会工作…@MartinEstes在这种情况下使用instanceof
操作符如何工作?您通常需要在编写答案时提供更多信息。此外,还有一个选项可以删除您的答案。
int R = 255;
int G = 255;
int B = 255;
if ((c.getRed() == R) && (c.getGreen() == G) && (c.getBlue() == B)) {
System.out.println("Found color");
} else {
System.out.println("Couldnt find color");
}