我需要为交通信号灯编写迭代方法。想法是红色是3分钟,然后它打开绿色,它是2分钟,然后它打开黄色,它是1分钟,然后它再次切换红色。迭代方法应该迭代状态机一分钟。我明白,它应该通过开关盒以某种方式完成,但我不知道如何....请帮助我。
public class TrafficLight
{
private enum State {RED, YELLOW, GREEN};
public void iterate()
{
switch(state)
{
case RED:
break;
case GREEN:
break;
case YELLOW:
break;
}
}
public void setTimeForState(State state, int time)
{
}
}
对不起,系统剪了我的帖子,还有那个setTimeForState方法,其中 更改红绿灯中特定颜色的等待时间。
答案 0 :(得分:0)
您需要在类中定义变量状态:
class TrafficLight {
enum State {
RED, YELLOW, GREEN
};
State state = State.GREEN;
public void iterate() throws InterruptedException {
switch (this.state) {
case RED:
System.out.println("RED");
Thread.sleep(1000);
this.state = State.GREEN;
break;
case GREEN:
System.out.println("GREEN");
Thread.sleep(1000);
this.state = State.YELLOW;
break;
case YELLOW:
System.out.println("YELLOW");
Thread.sleep(1000);
this.state = State.RED;
break;
}
}
并且在每种情况下等待一段时间将put状态转换为下一个值。
public static void main(final String[] args) throws InterruptedException {
final TrafficLight a = new TrafficLight();
while (true) {
a.iterate();
}
}
答案 1 :(得分:0)
这里是路灯模拟器,它使用定时器和开关:
import java.util.Timer;
import java.util.TimerTask;
public class TrafficLight {
static Timer timer =new Timer();
private enum State {
RED(3l), YELLOW(1l), GREEN(3l);
Long time;
State(Long time) {
this.time = time * 1000 * 60;
}
};
State state= State.RED;
boolean direction = true;
private static class ChangeState extends TimerTask {
public ChangeState(TrafficLight lights) {
this.lights = lights;
}
private final TrafficLight lights;
@Override
public void run() {
switch (lights.state){
case RED:
lights.direction = false;
lights.state = State.YELLOW;
break;
case YELLOW:
if (lights.direction)
lights.state = State.RED;
else
lights.state = State.GREEN;
break;
case GREEN:
lights.direction = true;
lights.state = State.YELLOW;
break;
}
System.out.println(lights.state);
timer.schedule(new ChangeState(lights),1000);// state.time);
}
};
public void run(){
System.out.println("state");
timer.schedule(new ChangeState(this), state.time);
}
public static void main(String[] a) {
(new TrafficLight()).run();
}
}