黑马程序员技术交流社区
标题:
关于交通灯管理系统的Lamp类
[打印本页]
作者:
跃动
时间:
2015-5-11 12:02
标题:
关于交通灯管理系统的Lamp类
在Java Project中,用的JRE System Library版本不能建立枚举类(已解决此问题),现在想用普通方法建立
交通灯的Lamp类的代码
,请问要怎么实现呢?求解ing...
作者:
major2015
时间:
2015-5-11 12:02
package com.itheima.demo1;
public class Lamp {
/*
* S2N,S2W,E2W,E2S是本类的核心,控制好他们就控制好了信号灯
*/
public final Lamp S2N = new Lamp("N2S", "S2W", false);
public final Lamp S2W = new Lamp("N2E", "E2W", false);
public final Lamp E2W = new Lamp("W2E", "E2S", false);
public final Lamp E2S = new Lamp("W2N", "S2N", false);
// S2N,S2W,E2W,E2S对应的oppo对象
public final Lamp N2S = new Lamp(false);
public final Lamp N2E = new Lamp(false);
public final Lamp W2E = new Lamp(false);
public final Lamp W2N = new Lamp(false);
// 右转信号灯
public final Lamp S2E = new Lamp(true);
public final Lamp E2N = new Lamp(true);
public final Lamp N2W = new Lamp(true);
public final Lamp W2S = new Lamp(true);
private String next;
private String oppo;
private boolean isGreen;
// 私有化构造器
private Lamp(String oppo, String next, boolean isGreen) {
this.oppo = oppo;
this.next = next;
this.isGreen = isGreen;
}
// 私有化构造器
private Lamp(boolean isGreen) {
this.isGreen = isGreen;
}
/*
* 通过信号灯名获得得对应信号灯
*/
public Lamp getLamp(String lamp) {
switch (lamp) {
case "S2N":
return S2N;
case "S2W":
return S2W;
case "E2W":
return E2W;
case "E2S":
return E2S;
default:
return null;// 不会被执行
}
}
public boolean isGreen() {
return isGreen;
}
public void toGreen() {
this.isGreen = true;
getLamp(oppo).isGreen = true;
System.out.println(this.toString() + "is green.");
}
public Lamp toRed() {
this.isGreen = false;
getLamp(oppo).isGreen = false;
getLamp(next).isGreen = true;
getLamp(getLamp(next).oppo).isGreen = true;
return getLamp(next);
}
@Override
public String toString() {
if (this == S2N) {
return "S2N";
} else if (this == S2W) {
return "S2W";
} else if (this == E2W) {
return "E2W";
} else if (this == E2S) {
return "E2S";
}
return null; // 不会被执行
}
}
复制代码
还没试,应该差不离了
作者:
跃动
时间:
2015-5-11 15:14
看了高新技术的枚举教程,彻悟
作者:
白水丶
时间:
2015-5-14 13:06
赞赞赞!!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2