I ve been working on a simple assignment, and the problem is that when I write the method for nextState within the main rountine itself, it works perfectly, but when I write it outside,just in the class but not in the main routine itself, and later call inside, it always goes from OFF to LOW and then the state of the lamp is still remaining OFF, I was trying to understand why myself but stuggle. Thank you for your help in advance!
enum State {
OFF,
LOW,
MEDIUM,
HIGH
}
public class ThreeWayLamp {
/*
* The method that changes the state of the lamp
* to the next enumerator in 'State'.
*/
private static void nextState(State lamp) {
if(lamp == State.OFF) {
lamp = State.LOW;
System.out.println("The lamp is set to "+lamp);
}else if(lamp == State.LOW){
lamp = State.MEDIUM;
System.out.println("The lamp is set to "+lamp);
}else if(lamp == State.MEDIUM){
lamp = State.HIGH;
System.out.println("The lamp is set to "+lamp);
}else if(lamp == State.HIGH){
lamp = State.OFF;
System.out.println("The lamp is set to "+lamp);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean run = true;
String answer;
State lamp = State.OFF;
System.out.println("Your command (OFF, LOW, MEDIUM, HIGH, STATE, NEXT, HELP, EXIT):");
while(run) {
try {
answer = scanner.nextLine();
switch(answer) {
case "OFF":
lamp = State.OFF;
System.out.println("The lamp is set to "+lamp);
break;
case "LOW":
lamp = State.LOW;
System.out.println("The lamp is set to "+lamp);
break;
case "MEDIUM":
lamp = State.MEDIUM;
System.out.println("The lamp is set to "+lamp);
break;
case "HIGH":
lamp = State.HIGH;
System.out.println("The lamp is set to "+lamp);
break;
case "STATE":
System.out.println("The lamp is set to "+lamp);
break;
case "NEXT":
nextState(lamp);
break;
case "HELP":
System.out.println("OFF: Set the lamp to OFF (default value)");
System.out.println("LOW: Set the lamp to LOW");
System.out.println("MEDIUM: Set the lamp to MEDIUM");
System.out.println("HIGH: Set the lamp to HIGH");
System.out.println("STATE: Print the current setting of the lamp");
System.out.println("NEXT: Change to the next setting");
System.out.println("HELP: Show a help menu");
System.out.println("EXIT: Quit the program");
break;
case "EXIT":
run = !run;
break;
default:
System.out.println("Please input a correct command");
}
}catch(Exception e) {
//Empty
}finally{
//Empty
};
}
scanner.close();
System.out.println("Goodbye");
}
} ```