public enum Lamp {
S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false),
N2S(null,null,false),N2E(null,null,false),W2E(null,null,false),W2N(null,null,false),
S2E(null,null,true),W2S(null,null,true),E2N(null,null,true),N2W(null,null,true);
private Lamp lamp;
private String oppsist; //定义相反方向的灯
private String nextlamp; //定义下一个灯
private boolean lighted; //定义boolean变量来判断灯的绿红情况,如果为true则为绿,如果为false则为红
Lamp(String oppsist,String nextlamp,boolean lighted ){
this.oppsist = oppsist;
this.nextlamp =nextlamp;
this.lighted =lighted;
}
public boolean islight(){ //判断是灯的情况,如果为true则为绿,如果为false则为红
return lighted;
}
public void setlight(){ //设置灯为绿,同时把对面的也设为绿
this.lighted =true;
if(oppsist!=null)
Lamp.valueOf(oppsist).setlight();
}
public Lamp setblack(){ //设置灯为红,对面的也设为红,并把下一个设为绿
this.lighted=false;
if(oppsist!=null){
Lamp.valueOf(oppsist).setblack();
}
System.out.println(name() + " lamp is green");
Lamp next = null;
if(nextlamp!=null){ //把下一个设为绿
next =Lamp.valueOf(nextlamp);
System.out.println(name()+"由红灯变为绿灯");
next.setlight();
}
return next;
}
}
当绿灯计时时间到,会由绿变为红,这个时候把它的对面也变为红,它的下一个设为绿。一个灯由红变为绿,它的对面也设为绿为绿,这样在里面通过计时器循环的设置灯的红绿情况,它们内部是有顺序的。 |