Reputation: 1632
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!
Upvotes: 0
Views: 179
Reputation: 3809
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))
Upvotes: 2
Reputation: 528
Can do it like this:
if (!isWithinBounds(red, green, blue)) {
...
}
And create this method:
private static boolean isWithinBounds(int... values) {
boolean withinBounds = values.length > 0;
for (int value : values) {
withinBounds &= value > 0 && value < 256;
}
return withinBounds;
}
Upvotes: 0
Reputation: 4411
red, green and blue are integers and you should check separately not with OR operation.. you can use OR operation for boolean variables
e.g
red > 255 || green > 255 || blue > 255
Upvotes: 1
Reputation: 4564
You can't compare all three things at once in a single comparison like this:
(red || green || blue) > 255
You have to separate them into separate comparisons.
red > 255 || green > 255 || blue > 255
Upvotes: 1