Task. Turn on and off the lamp at the specified time during the day. I need to know how to fix my code according to the information below. I also need to know if I am using the timer class correctly, i.e. is my code working correctly? The code may work, but it may be a bad design that will cause problems later. I do not want this to happen.
Exit (this is not the result that I really wanted :() -
This is the main program Current time is - xxx Future time is - xxx+5sec Future time is - xxx+10sec Main program ends Bulb B1 is OFF
The required conclusion is
This is the main program Current time is - xxx Future time is - xxx+5sec Future time is - xxx+10sec Bulb B1 is ON //first on Bulb B1 is OFF //then off Main program ends//This should always be in the end.
How to fix the code below to get what I want?
Bulb Class
class Bulb { private boolean state = false;//On or off private String name; Bulb(String name){ this.name = name; } public void setState(boolean state){ this.state = state; if(this.state == true){ System.out.println("Bulb " + name + " is ON"); }else{ System.out.println("Bulb " + name + " is OFF"); } } public boolean getState(){ return this.state; } }
BulbJob which is a TimerTask
import java.util.*; class BulbJob extends TimerTask{ private Bulb bulbToHandle; private boolean setBulbStateEqualTo; BulbJob(Bulb toHandle){ this.bulbToHandle = toHandle; }
BulbScheduler class - this is the schedule when the bulb is on or off.
import java.util.*; @SuppressWarnings( "deprecation" ) class BulbScheduler { public static void main(String args[]) throws InterruptedException{ System.out.println("This is the main program"); Timer time = new Timer(); Bulb b1 = new Bulb("B1"); BulbJob bj = new BulbJob(b1); bj.setBulbStateEqualTo(true);
source share