Here is an example of how you could do it with a bit of Java 9:
public static void main(String[] args) throws ParseException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter your color\n" +
"BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
List<Color> colorArray= new ArrayList<>();
Map<String, Color> colorMap = Map.ofEntries(entry("BLUE", Color.BLUE),
entry( "BLACK", Color.BLACK),
entry( "ORANGE", Color.ORANGE)); // TODO: add more colours
while(sc.hasNext()) {
String next = sc.next();
Color c = colorMap.get(next);
if(c == null) {
if("END".equals(next)) {
break;
}
System.err.printf("Sorry, could not find %s%n", next);
}
else {
colorArray.add(c);
System.out.printf("Added %s%n", c);
}
}
System.out.println(colorArray);
}
This is the output of a sample run:
Enter your color
BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:
> BLUE
Added java.awt.Color[r=0,g=0,b=255]
> BLACK
Added java.awt.Color[r=0,g=0,b=0]
> ORANGE
Added java.awt.Color[r=255,g=200,b=0]
> END
[java.awt.Color[r=0,g=0,b=255], java.awt.Color[r=0,g=0,b=0], java.awt.Color[r=255,g=200,b=0]]
Here is another version based on @VHS ideas using reflection:
public static void main(String[] args) throws ParseException, ClassNotFoundException, IllegalAccessException {
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter your color\n" +
"BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
List<Color> colorArray= new ArrayList<>();
Class<Color> colorClass = Color.class;
while(sc.hasNext()) {
String next = sc.next();
try {
Color c = colorClass.cast(colorClass.getField(next.toLowerCase()).get(null));
colorArray.add(c);
System.out.printf("Added %s%n", c);
} catch (NoSuchFieldException e) {
if("END".equals(next)) {
break;
}
System.err.printf("Sorry, could not find %s%n", next);
}
}
System.out.println(colorArray);
}
Ideally you would combine both ideas (use a map and reflection), so that you support the declared colours + non declared colours in java.awt.Color.