这是我的代码:
import java.util.Scanner;
public class RGBColor
{
// instance variables
private int _red;
private int _green;
private int _blue;
/**
* Constructor for objects of class RGBColor
*/
public RGBColor()
{
// initialise instance variables
_red=_green=_blue=0;
}
public RGBColor(int red, int green, int blue)
{
if(((red || green || blue) > 255) || ((red || green || blue) < 0))
red=_green=_blue=0;
else
{
_red = red;
_green = green;
_blue = blue;
}
}
public RGBColor(RGBColor other)
{
System.out.print("Please enter 3 integers which will represent colors: ");
System.out.println("First one, RED.");
Scanner getColors = new Scanner(System.in);
System.out.println("Second one, GREEN.");
Scanner getGreen = new Scanner(System.in);
System.out.println("Third one, BLUE.");
Scanner getBlue = new Scanner(System.in);
}
public int getRed()
{
return _red;
}
public int getGreen()
{
return _green;
}
public int getBlue()
{
return _blue;
}
public void setRed(int num)
{
if(((red || green || blue) > 255) || ((red || green || blue) < 0))
break;
else
_red = num;
}
public void setGreen(int num)
{
_green = num;
}
public void setBlue(int num)
{
blue_ = num;
}
}
我在这方面遇到了问题:
if(((red || green || blue) > 255) || ((red || green || blue) < 0))
二元运算符||的错误操作数类型。任何想法如何解决它?我的代码非常简单,所以我相信我不必解释任何事情。我只是不明白为什么我无法检查整数是否大于255,例如先谢谢你!
答案 0 :(得分:2)
您需要单独测试每个变量:
if(red > 255 || green > 255 || blue > 255 || red < 0 || green < 0 || blue < 0)
然而,为了好的代码我会写一个函数:
private static boolean anyNotValid(int... values) {
for(int i: values) {
if(i < 0 || i > 255) return true;
}
return false;
}
...然后您可以将其称为:
if(anyNotValid(red, green, blue))
答案 1 :(得分:1)
红色,绿色和蓝色是整数,你应该单独检查而不是OR操作..你可以对布尔变量使用OR运算
例如
red > 255 || green > 255 || blue > 255
答案 2 :(得分:1)
你无法在一次比较中同时比较所有这三件事:
(red || green || blue) > 255
你必须将它们分开进行单独的比较。
red > 255 || green > 255 || blue > 255
答案 3 :(得分:0)
可以这样做:
if (!isWithinBounds(red, green, blue)) {
...
}
创建此方法:
private static boolean isWithinBounds(int... values) {
boolean withinBounds = values.length > 0;
for (int value : values) {
withinBounds &= value > 0 && value < 256;
}
return withinBounds;
}