本帖最后由 黑马_许芸 于 2012-9-3 21:26 编辑
有看过这个视频的同学吗?看过的同学应该知道张老师在第一次运行该程序的时候发现“"绿灯从 "+name()+" ---------->切换为:"+next”这句话输出不了。然后老师在Lamp中改了几行代码后就运行正常了。可是我跟着老师改了之后还是无法运行成功。我的Lamp类的代码如下,其他代码跟老师都一样的就不贴了。代码中的红色字体部分应该就是症结所在,求高手指点,我实在看不出来错在哪儿了。- package com.isoftstone.interview.traffic;
- public enum Lamp
- {
- S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false), //有业务逻辑的4个灯
- N2S(null,null,false) ,N2E(null,null,false) ,W2E(null,null,false) ,W2N(null,null,false) , //一一和上面的4个灯对应
- S2E(null,null,true) ,E2N(null,null,true) ,N2W(null,null,true) ,W2S(null,null,true) ; //常绿的4个灯
-
- private boolean lighted;
- private String opposite;//这里要把想对应的Lamp用字符串代替,是因为S2N(N2S),Cannot reference a field before it is defined.
- private String next;
-
- private Lamp(String opposite,String next,boolean lighted)
- {
- this.opposite = opposite;
- this.next = next;
- this.lighted = lighted;
- }
-
- private Lamp()
- {
- // TODO Auto-generated constructor stub
- }
-
- public boolean isLighted()
- {
- return lighted;
- }
-
- public void light()
- {
- System.out.println("light: "+name());
- this.lighted = true;
- System.out.println(name()+" lamp is green ,下面总共应该有6个方向能看到汽车穿过 !");
- if (opposite != null) //这个条件判断很重要,否则就是死循环了
- {
- Lamp.valueOf(opposite).light();
- }
- }
-
- public Lamp blackOut()
- {
- this.lighted = false;
- if (opposite != null) //这个条件判断很重要,否则就是死循环了
- {
- Lamp.valueOf(opposite).blackOut();
- }
- <font color="red">System.out.println(name()); // 这里我打印出来的结果是N2S,可是我明明在LampController中写的currentLamp = Lamp.S2N;
- System.out.println(next); //因为现在当前的灯变为N2S,所以next就变成null了。</font>
- Lamp nextLamp = null;
- if (next != null)
- {
- nextLamp = Lamp.valueOf(next);
- System.out.println("绿灯从 "+name()+" ---------->切换为:"+next);
- nextLamp.light();
- }
-
- return Lamp.valueOf(opposite);
- }
- }
复制代码 |