Skip to content
Advertisement

Why doesn’t my if statement work with (red || green || blue) > 255

here’s my code:

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;
}
}

I’m having problems in this line:

if(((red || green || blue) > 255)  || ((red || green || blue) < 0))

bad operand types for binary operator ||. Any ideas how to fix it? My code is very simple so I believe I don’t have to explain anything. I just don’t understand why I can’t check if integer is greater than 255 for e.g. Thanks on advance!

Advertisement

Answer

You need to test each variable seperately:

if(red > 255 || green > 255 || blue > 255 || red < 0 || green < 0 || blue < 0)

However, for good code I’d write a function:

private static boolean anyNotValid(int... values) {
    for(int i: values) {
        if(i < 0 || i > 255) return true;
    }
    return false;
}

… which you could then call as:

if(anyNotValid(red, green, blue)) 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement