如何接受用户的角色来代表彩虹色的第一个字母。即紫罗兰,靛蓝,蓝色,绿色,黄色,橙色,红色。该字符可以是大写或小写。在屏幕上打印相应的颜色。对于任何其他字符打印'无效颜色'
答案 0 :(得分:1)
Color color;
try {
Field field = Class.forName("java.awt.Color").getField("yellow");
color = (Color)field.get(null);
} catch (Exception e) {
color = null; // Not defined
}
答案 1 :(得分:0)
我认为这就是你想要的
char input='y';
// This is NOT the best way, but it is readable
input=(input+"").toLowerCase().toCharArray()[0];
// This is a better approach, but far more difficult to understand
if(input>=65 && input<=90) input+=32;
// Edit these colors if you don't like them
Color v=new Color(128,0,255); // Violet
Color i=new Color(111,0,255); // Indigo
Color b=new Color(0,0,255); // Blue
Color g=new Color(0,255,0); // Green
Color y=new Color(255,255,0); // Yellow
Color o=new Color(255,128,0); // Orange
Color r=new Color(255,0,0); // Red
// I don't know if this is the best way, but it works and you used the [switch-statement] tag
Color c=null;
switch(input) {
case 'v':
c=v;
break;
case 'i':
c=i;
break;
case 'b':
c=b;
break;
case 'g':
c=g;
break;
case 'y':
c=y;
break;
case 'o':
c=o;
break;
case 'r':
c=r;
break;
default:
break;
}
// Outputting
if(c==null) {
System.out.println("Invalid character");
} else {
System.out.println("R:"+c.getRed()+" G:"+c.getGreen()+" B:"+c.getBlue()+" A:"+c.getAlpha());
}