我需要为红绿灯写迭代法。它的思想是,红色是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的方法,它改变了交通灯中特定颜色的等待时间。
发布于 2014-11-05 15:48:40
您需要在类中定义变量状态:
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();
}
}发布于 2014-11-05 16:12:50
这里是路灯模拟器,它使用计时器和开关:
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();
}
}https://stackoverflow.com/questions/26761229
复制相似问题