Enum State Machine
Completed
Create enum Light { RED, GREEN, YELLOW } with a method next() using a switch (RED→GREEN→YELLOW→RED). Read a starting light and a number of steps; print each state as it changes, then its ordinal().
Input
Line 1: light name. Line 2: steps.
Output
One name per step, then the final ordinal.
Example
Input
RED 4
Output
GREEN YELLOW RED GREEN 1
Editor
Java
Hints
Light.valueOf("RED") converts text to the constant.
Inside a switch on an enum, write case RED, not case Light.RED.
Solution explanation
Enums make invalid states impossible - you can't have a light called PURPLE.
Show solution
import java.util.Scanner;
enum Light {
RED, GREEN, YELLOW;
Light next() {
switch (this) {
case RED:
return GREEN;
case GREEN:
return YELLOW;
default:
return RED;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Light light = Light.valueOf(sc.next());
int steps = sc.nextInt();
for (int i = 0; i < steps; i++) {
light = light.next();
System.out.println(light);
}
System.out.println(light.ordinal());
}
}