我在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()像魅力一樣工作。謝謝! –