Is there anyway to put this test in a separate class? I tried but was unsuccessful.
public class TrafficLightprj 
{
    public enum TrafficLight 
    {  
        RED(1),  
        GREEN(2),  
        YELLOW(3);
        private final int duration; 
        TrafficLight(int duration) { 
            this.duration = duration; 
        }  
        public int getDuration() { 
            return this.duration; 
        } 
        public static void main(String[] args) 
        {
            for(TrafficLight light: TrafficLight.values())
            {
               System.out.println("The traffic light value is: " +light);
               System.out.println("The duration of that trafic light value is: " + light.getDuration());
            }
        }   
    }
}
                I'm not sure I understand what you mean in your question, so I'll answer to what I think you are asking.
An enum can be its own file in Java. For example, you could have a file called TrafficLight which, inside, is:
public enum TrafficLight {  
    RED(1),  
    GREEN(2),  
    YELLOW(3);
    private final int duration; 
    TrafficLight(int duration) { 
        this.duration = duration; 
    }  
    public int getDuration() { 
        return this.duration; 
    } 
}
You then can use this enum from your test project (TrafficLightPrj.java). Like so:
public class TrafficLightprj {
    public static void main(String[] args) {
        for(TrafficLight light: TrafficLight.values()) {
            System.out.println("The traffic light value is: " +light);
            System.out.println("The duration of that trafic light value is: " +light.getDuration());
        }
    }
}
                        You need to put it in a different .java file itself. You can't have more than one public class / enum in a single .java file.
TrafficLightprj.java
public class TrafficLightprj {
    public static void main(String[] args) {
        for(TrafficLight light: TrafficLight.values()){
            System.out.println("The traffic light value is: " +light);
            System.out.println("The duration of that trafic light value is: "  +light.getDuration());
        }
    }
}
TrafficLight.java
public enum TrafficLight {  
    RED(1),  
    GREEN(2),  
    YELLOW(3);
    private final int duration; 
    TrafficLight(int duration) { 
        this.duration = duration; 
    }  
    public int getDuration() { 
        return this.duration; 
    }
} 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With