我在AP计算机科学课中使用GridWorld,并且我们正在做的一部分工作是更改错误(对象)的颜色。我已经找到了一个非常基本的方法来做到这一点,但我试图将字符串合并,以允许用户键入他想要的bug的颜色,而不必为RGB输入数值。我可以通过键入“red”并让字符串存储该字符串值来获得我想要的颜色。但是,如何将该字符串转换为颜色?我不太确定我是否足够清楚地描述了这一点,但是我附上了我的代码,希望有人能够理解并能够提供帮助。设置对象的颜色
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));
}
+1使用枚举,但@OP,枚举不包括在APCS课程中,所以请准备好让老师询问您对它们的使用。 – Vulcan
不知道“枚举”是什么,但为了这些目的.equals()像魅力一样工作。谢谢! –