这是我的代码:

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,例如提前谢谢!

最佳答案

您需要分别测试每个变量:

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))

10-07 13:27