我正在尝试编写一个程序,在四向交叉点显示灯光序列。
指令是:
在任何特定时间,交通只能朝一个方向移动。交通灯有三种颜色:RED,YELLOW和GREEN。基于一个事件。灯光以同步方式改变颜色,以便安全驾驶。定义一个名为“TrafficLight”的类,它有两个方法。一个叫做“改变”,另一个叫做“getColor”。在一个单独的类“Assignment5”中,通过主入口点,我希望您为北/南流量创建两个TrafficLight实例,为东/西流量创建两个。使用对象提供的两种方法我希望您显示已正确模拟四向交通灯。
到目前为止,我有:
public class TrafficLight {
/**
* @param args
*/
public TrafficLight(int c){
this.c = c;
}//end constructor
public int getC(){
return c;
}
java.lang.String getColor;
String n = "GYR";
String s = "GYR";
String e = "GYR";
String w = "GYR";
public void change(){
int c = 1;
while (c <= 4){
if (c == 1){
n.charAt(2);
s.charAt(2);
e.charAt(0);
w.charAt(0);
c++;
}
else if (c == 2){
n.charAt(2);
s.charAt(2);
e.charAt(1);
w.charAt(1);
c++;
}
else if (c == 3){
n.charAt(0);
s.charAt(0);
e.charAt(2);
w.charAt(2);
c++;
}
else if (c == 4){
n.charAt(1);
s.charAt(1);
e.charAt(2);
w.charAt(2);
c++;
}
while (c >= 5)
if (c-4 == 1){
n.charAt(2);
s.charAt(2);
e.charAt(0);
w.charAt(0);
c++;
}
else if (c-4 == 2){
n.charAt(2);
s.charAt(2);
e.charAt(1);
w.charAt(1);
c++;
}
else if (c-4 == 3){
n.charAt(0);
s.charAt(0);
e.charAt(2);
w.charAt(2);
c++;
}
else if (c-4 == 4){
n.charAt(1);
s.charAt(1);
e.charAt(2);
w.charAt(2);
c++;
}
System.out.println(n);
System.out.println(s);
System.out.println(e);
System.out.println(w);
}//end inner while loop
}//end 'change'
private int c;
}//end class
示例输出应如下所示:
Traffic light event 1:
North light: Red
South light: Red
East light: Green
West light: Green
Traffic light event 2:
North light: Red
South light: Red
East light: Yellow
West light: Yellow
Traffic light event 3:
North light: Green
South light: Green
East light: Red
West light: Red
Traffic light event 4:
North light: Yellow
South light: Yellow
East light: Red
West light: Red
Traffic light event 5:
North light: Red
South light: Red
East light: Green
West light: Green
Traffic light event 6:
North light: Red
South light: Red
East light: Yellow
West light: Yellow
Traffic light event 7:
North light: Green
South light: Green
East light: Red
West light: Red
Traffic light event 8:
North light: Yellow
South light: Yellow
East light: Red
West light: Red
Traffic light event 9:
North light: Red
South light: Red
East light: Green
West light: Green
Traffic light event 10:
North light: Red
South light: Red
East light: Yellow
West light: Yellow
Traffic light event 11:
North light: Green
South light: Green
East light: Red
West light: Red
Traffic light event 12:
North light: Yellow
South light: Yellow
East light: Red
West light: Red
我将如何实现这一目标?有什么想法吗?