Write a ThreeWayLamp class that models the behavior of a lamp that uses a three-
ID: 3761004 • Letter: W
Question
Write a ThreeWayLamp class that models the behavior of a lamp that uses a three-way bulb. These bulbs have actually four possible states: off, low light, medium light, and high light. Each time the switch is activated, the bulb goes to the next state (from high, the next state is off, from off to low etc). The ThreeWayLamp class has a single method called switch() which takes a single int parameter indicating how many times the switch is activated. (you need to throw an exception if its negative). The switch() method should simply print out to System.out, a message indicating the state of the bulb after it has changed java program
Explanation / Answer
package current;
public class ThreeWayLamp {
public static void main(String[] args) {
ThreeWayLamp lamp = new ThreeWayLamp();
lamp.switchLamp(1);
lamp.switchLamp(5);
lamp.switchLamp(3);
}
private STATE currentState;
public ThreeWayLamp() {
currentState = STATE.HIGH_LIGHT;
}
public enum STATE {
//Each time the switch is activated, the bulb goes to the next state (from high, the next state is off, from off to low etc)
HIGH_LIGHT(1, "HIGH LIGHT"), OFF(2, "OFF"), LOW_LIGHT(3, "LOW LIGHT"),MEDIUM_LIGHT(4,"MEDIUM LIGHT");
private int val;
private String stateStr;
STATE(int val, String stateStr) {
this.val = val;
this.stateStr = stateStr;
}
public int getVal() {
return val;
}
public static STATE getState(int stateId) {
if(stateId == HIGH_LIGHT.val)
return HIGH_LIGHT;
if(stateId == OFF.val)
return OFF;
if(stateId == LOW_LIGHT.val)
return LOW_LIGHT;
if(stateId == MEDIUM_LIGHT.val)
return MEDIUM_LIGHT;
return null;
}
public String toString() {
return stateStr;
}
}
public void switchLamp(int nTimesActivated) {
//Each time the switch is activated, the bulb goes to the next state (from high, the next state is off, from off to low etc)
//starting state is high, high->off->low->medium->high
if(nTimesActivated < 0)
throw new IllegalArgumentException("No of times activated should be postive");
STATE prevState = currentState;
int val = (currentState.getVal()+nTimesActivated) % 4;
currentState = STATE.getState(val);
System.out.println("Initial State: "+prevState.toString()+" No of times Activated: "+nTimesActivated
+" Current State: "+currentState.toString());
}
}
------------output-------------
Initial State: HIGH LIGHT No of times Activated: 1 Current State: OFF
Initial State: OFF No of times Activated: 5 Current State: LOW LIGHT
Initial State: LOW LIGHT No of times Activated: 3 Current State: OFF
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.