Pergunta

I am using GridWorld in my AP Computer Science class, and part of what we are doing is changing the color of the bug (an object). I have found a very basic way to do this but am trying to incorporate strings to allow the user to type in what color he would like the bug to be instead of having to put in number values for RGB. I am able to get the string value to be the color that I want, by typing in, "red" and having the string store that. But how would I get that string to translate into the color? I'm not really sure if I worded this clearly enough but I have attached my code so hopefully someone will understand and can help.

Color red = new Color (255, 0, 0);
Color green = new Color (0, 255, 0);
Color blue = new Color (0, 0, 255);

System.out.println("What color would you like the first bug to be? (red, green, blue)");
String name = "color1";
String color1 = keyboard.next();

if (color1 == "red")
{
   world.add (new Location (bugx1, bugy1), new Bug(red));
}
if (color1 == "blue")
{
   world.add (new Location (bugx1, bugy1), new Bug(blue));
}
if (color1 == "green")
{
   world.add (new Location (bugx1, bugy1), new Bug(green));
}
Foi útil?

Solução

This old chestnut...

When comparing Strings in java, you must use .equals(). The == operator is true only if both operands are the same exact object. Try this:

if (color1.equals("red"))

This is a common "mistake" made by programmers familiar with javascript, where the == operator would work as you have coded it. IMHO, the "mistake" is actually in the java language specification - they should have allowed == to execute equals() and use === for identity comparison (which is rarely actually used).


To do this properly, I recommend using an enum for the colors. Then your code would be just one line:

public enum BugColor {
    red(255, 0, 0),
    green(0, 255, 0),
    blue(0, 0, 255);

    private final Color color;

    BugColor(int r, int g, int b) {
        color = new Color(r, g, b);
    }

    public Color getColor() {
        return color;
    }
}

then simply:

String color1 = keyboard.next();
world.add (new Location (bugx1, bugy1), new Bug(BugColor.valueOf(color1).getColor()));

If Color is an interface, you can simplify and improve your code by making the enum BugColor extends Color - I'll leave the implementation as an exercise for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top