java Color随机产生颜色,取值范围为red、blue、yellow、green、orange
时间: 2023-10-20 13:07:15 浏览: 109
可以使用Java中的Random类来随机产生颜色。可以将五种颜色存储在一个数组中,然后使用Random类生成一个随机的索引,从而随机选择一种颜色。下面是一个示例代码:
```java
import java.awt.Color;
import java.util.Random;
public class ColorRandomizer {
public static void main(String[] args) {
String[] colors = {"red", "blue", "yellow", "green", "orange"};
Random random = new Random();
int index = random.nextInt(colors.length);
String colorString = colors[index];
Color color = null;
switch (colorString) {
case "red":
color = Color.RED;
break;
case "blue":
color = Color.BLUE;
break;
case "yellow":
color = Color.YELLOW;
break;
case "green":
color = Color.GREEN;
break;
case "orange":
color = Color.ORANGE;
break;
default:
break;
}
System.out.println("Random color: " + colorString);
System.out.println("RGB value: " + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue());
}
}
```
运行以上代码会随机选择一种颜色,并输出该颜色的名称和RGB值。
阅读全文