模拟红绿灯程序

package traffic;

//---------------------------------------------------------------------------------------
public class Colors {

	private RGY lamp = new RGY();
	
	
	public void Red() {		
		lamp.RGYlight(IEType.RED.Seconds(),IEType.RED.light());	
	}
	
	public void Green() {
		lamp.RGYlight(IEType.GREEN.Seconds(),IEType.GREEN.light());
	}
	
	public void Yellow() {
		lamp.RGYlight(2,"Yellow");
	}

	
}


//---------------------------------------------------------------------------------------
package traffic;

import java.util.HashMap;

public interface IEColor {

	public String Description();
	public String Code();
	public Integer Seconds();
	public String light();
	
	
}


//---------------------------------------------------------------------------------------
package traffic;



public enum IEType implements IEColor{
	
	RED(	4,	"Red Wait:",	"即将红灯 5s",	"Red"),
	GREEN(	5,	"Green Pass:",	"即将绿灯 6s",	"Green"),
	YELLOW(	2,	"Yellow Slow:",	"即将黄灯 3s",	"Yellow"),

	REDLINE(   0, "RedLineNeedStop",         "StopLine",  "STOP"),
	GREENLINE( 1, "GreenLineToPass",         "PassLine",  "PASS"),
	YELLOWLINE(2, "YellowLineShouldBeWait",  "WaitLine",  "WAIT");
	
	

	
	private final Integer seconds;
	private final String description;
	private final String code;
	private final String light;
	
	
	
	private IEType(Integer seconds,String description, String code, String light) {
		this.seconds = seconds;
		this.description = description;
		this.code = code;
		this.light = light;
	}

	@Override
	public String Description() {
		return this.description;
	}

	@Override
	public String Code() {
		return this.code;
	}

	@Override
	public Integer Seconds() {
		return this.seconds;
	}

	public String light() {
		return this.light;
	}

	
	/*
	 * enum_key(Integer) get ENUM 
	 */
	public static IEType getEnumByCode(int code) {
		for(IEType em : IEType.values()) {
			if(em.Seconds().equals(code)) {
				if(code == 2) {
					em = IEType.YELLOWLINE;				
				}	
				return em;
			}			
		}
		throw new IllegalArgumentException("error in IEType.getEnumByCode");
		
	}

	

	
	public static IEType getLightByCode(Integer code) {
		switch(code) {
			case 0:
				return IEType.RED;
			case 1:
				return IEType.GREEN;
			case 2 :
				return IEType.YELLOW;
			default :
				throw new NullPointerException("code error in ENUM IntegerCode");
		}

	}
	
	
	public static String SecToLight(Integer code) {
		for(IEType type : IEType.values()) {
			return type.light;
		}
		throw new NullPointerException("SecToLight code to light!");
	}
	

}


//---------------------------------------------------------------------------------------
package traffic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class ListSet {

	
	
	public static List<String> setList() {
		List<String> list = new ArrayList<>();
		list.add(IEType.RED.light());
		list.add(IEType.GREEN.light());
		list.add(IEType.YELLOW.light());		
		return list;
	}
	
	public static List<String> descriptionList(){
		List<String> deslist = new ArrayList<>();
		deslist.add(IEType.RED.Description());
		deslist.add(IEType.GREEN.Description());
		deslist.add(IEType.YELLOW.Description());		
		return deslist;
	}
	
	/**
	 * NOT USE
	 * @param DTL
	 * @return index对应的value
	 */
	public static String DescriptionToLight(String DTL) {
		for(String DTK : setList()) {
			if(DTL.contains(DTK)) {
				//         indexOf获取DTK对应索引;get()获取对应索引value
				return descriptionList().get(setList().indexOf(DTK));
			}		
		}
		throw new NullPointerException("DTL is null in DescriptionToLight by ListSet");
		
	}

	
	public HashMap<String,String> lightToDescription() {
		HashMap<String, String> lightdes = new HashMap<>();
		lightdes.put(IEType.RED.light(), IEType.RED.Description());
		lightdes.put(IEType.GREEN.light(), IEType.GREEN.Description());
		lightdes.put(IEType.YELLOW.light(), IEType.YELLOW.Description());
/**
		// for list
		for(String item : setList()) {
			if(ld.equals(item)) {
				return lightdes.get(item);
			}			
		}		
		throw new NullPointerException("lightToDescription Error!");
*/
		return lightdes;
		
	}
	
	
	public String lightToDes(String lr) {
		for(String it : setList()) {
			if(lr.equals(it)) {
				return lightToDescription().get(it);
			}
		}
		
		return "xxxxxx";
	}

	
	
	
	
	
	public String lightToCode(String lc) {
		HashMap<String, String> lightcode = new HashMap<>();
		lightcode.put(IEType.RED.light(), IEType.RED.Code());
		lightcode.put(IEType.GREEN.light(), IEType.GREEN.Code());
		lightcode.put(IEType.YELLOW.light(), IEType.YELLOW.Code());
	
		
		
		Set<String> keys = lightcode.keySet();
		for(Object light : keys) {
			if(lc.equals(light)) {
				return lightcode.get(light);
			}
		}
		throw new NullPointerException("lightToCode error!!!");

	}
	

	
	
}


//---------------------------------------------------------------------------------------

package traffic;

import java.util.HashMap;
import java.util.logging.Logger;




public class MapLine {
	
	Logger logger = Logger.getLogger(MapLine.class.getName());
	
	public HashMap<Integer, String> setMap(){
		HashMap<Integer, String> Line = new HashMap<>();
		Line.put(IEType.REDLINE.Seconds(), IEType.REDLINE.Code());
		Line.put(IEType.GREENLINE.Seconds(), IEType.GREENLINE.Code());
		Line.put(IEType.YELLOWLINE.Seconds(), IEType.YELLOWLINE.Code());
		return Line;
	}

	
	//Stop Pass Wait line
	public String getMapLine(Integer code) {
		if(setMap().containsKey(code)) {
//			logger.warning("ERROR");
			return setMap().get(code);
		}
		throw new IllegalArgumentException("Code Error in getMapLine OF MapLine.Class!");
	}


	// :5s
	public String getLineByCode(Integer code) {	
		if(setMap().containsKey(code)) {
			return MapStr.RsecWait(code);			
		}else {
			throw new IllegalArgumentException("Error in getLineByCode OF MapLine.Class");
		}	
	}

	
	// 
	public String getLineByLine(Integer n) {
		SwitchSleep.Sleep();
		return getMapLine(n) +":"+getLineByCode(n);		
	}
	
	
}


//---------------------------------------------------------------------------------------

package traffic;

public enum MapStr {

	REDSEC   (0, ":5s", "Red"),
	GREENSEC (1, ":6s", "Gree"),
	YELLOWSEC(2, ":3s", "Yellow");
	
	
	private final Integer second;
	private final String wait;
	private final String light;
	
	private final static String REDS = String.valueOf(IEType.RED.Seconds() + 1);
	private final static String GREENS = ":"+Integer.toString(IEType.GREEN.Seconds() + 1);
	private final static String YELLOWS = ":"+IEType.YELLOW.Seconds() + 1 +"";
	
	
	
	
	private MapStr(Integer seconds, String wait, String light) {
		this.second = seconds;
		this.wait = wait;
		this.light = light;
	}

	public Integer getSecond() {
		return second;
	}

	public String getWait() {
		return wait;
	}

	public String getLight() {
		return light;
	}
	
	
	public static String getWaitSec(int code) {
		for(MapStr eu : MapStr.values()) {
			if(eu.getSecond().equals(code)) {
				return eu.wait;
			}
		}
		throw new IllegalArgumentException("MapStrError in line39(getWaitSec) cause by code");
		
	}
	
	public static boolean foreachsecond(Integer code) {
		for(MapStr ec : MapStr.values()) {
			if(ec.getSecond().equals(code)) {
				return true;
			}
		}		
		return false;
	}

	//code.equals(REDSEC.second) || code.equals(GREENSEC.second) || code.equals(YELLOWSEC.second) 
	public static String RsecWait(Integer code) {
		if(foreachsecond(code) ) {
			return IEType.getEnumByCode(code).Description() + MapStr.getWaitSec(code);
		}else {
			throw new IllegalArgumentException("MapStrResWait Not In code error in line57");
		}
	}	

}


//---------------------------------------------------------------------------------------

package traffic;

import java.util.Arrays;
import java.util.logging.*;



public class RGY {

	private static int lightStatus = 0;
	private int seconds;
	private State s = new State();
	private static Colors col = new Colors();
	private String[] LightArr = {IEType.RED.light(),IEType.GREEN.light(),"Yellow"};
	private static Logger logger = Logger.getLogger(RGY.class.getName());
	private MapLine line = new MapLine();
	
	private Integer countNum = 1;
	
		

	

	public boolean Red() {
		return lightStatus == 0;
	}
	public boolean Green() {
		return lightStatus == 1;
	}
	public boolean Yellow() {
		return lightStatus == 2;
	}
	public int lightStatus() {
		lightStatus = (lightStatus + 1) % 3; //取模运算保证灯的状态在0-2之间循环切换 
		System.out.println("Debug:" + countNum +"->"+ clby(lightStatus));

		String l = line.getLineByLine(lightStatus);
		System.out.println(l);
		
		countNum ++ ;
				
		return lightStatus;
	}
	
	
	// get color by lightStatus
	public String clby(int light) {
		return get(light);
	}

	//get light to clby()
	public String get(int n) {
//		return LightArr[n];
		return IEType.getLightByCode(n).light();
	}
	
	
	public void Run() {
		if(Red()) {
			col.Red();
		}else if(Green()) {
			col.Green();
		}else {
			col.Yellow();
		}
		SwitchSleep.Switch();
	}

	
	
	//切换 
	@SuppressWarnings("static-access")
	public void RGYlight(int sec, String color ) {
		//
		if(!Arrays.asList(LightArr).contains(color)) {
			logger.log(logger.getLevel().WARNING, "YOUR COLOR WRONG!!!");
			throw new ArithmeticException("your color wrong!!!");		
		}else {			
			seconds = sec;
			System.out.println(s.RC(color));
			SwitchSleep.Sleep();// Wait 前置
					
			for(int i=0;i<seconds+sec;i++) {					
				System.out.println(s.RD(color)+seconds);
				SwitchSleep.Sleep();
				seconds--;
			}
			
			
			System.out.println(s.RD(color)+ seconds);
			
			//switch Delay 1s
			SwitchSleep.Sleep();
			
			System.out.println("切换中");			
		}		
	}
	
	
	
	
	
}


//---------------------------------------------------------------------------------------

package traffic;

import java.util.Scanner;

public class Start {


	public static Scanner scanner = new Scanner(System.in);
	private static boolean isRunning;
	public static Time t = new Time();	
	public static RGY R = new RGY();
	private static final String TIMELOCAL = t.getAll();
			
			
//											t.getTime() + "\n" 
//											+ t.getlocal() + "\n" 
//											+ t.getDividingLine() + "\n"
//											+ t.getWorkTime();
	
	
	
	public static void Start() {
		
		System.out.println(TIMELOCAL);
        SwitchSleep.Sleep();
        while (isRunning = true) { 
        	R.Run();
        }        
       scanner.close();  
       
	}


}


//---------------------------------------------------------------------------------------

package traffic;

import java.util.logging.Logger;

public class State {
	
	Logger logger = Logger.getLogger(State.class.getName());
	ListSet ls = new ListSet();
	
	public String RD(String r) {
		return ls.lightToDes(r);
	}

	
	
	
	public String RC(String r) {		
		
		try {
			if(r.equals(IEType.RED.light())) {	
				return IEType.RED.Code();
			}
			if(r.equals(IEType.GREEN.light())) {
				return IEType.GREEN.Code();
			}
			if(r.equals("Yellow")){
				return IEType.YELLOW.Code();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		
		return ls.lightToCode(r);

	}

	
	
	
	
}





//---------------------------------------------------------------------------------------

package traffic;

public class SwitchSleep {


	private static RGY lamp = new RGY();
	private static State st = new State();

	public static void Switch() {

	   lamp.lightStatus();
       if(lamp.Red()) {  
    	   Sleep();
    	   st.RD(IEType.RED.light());
       }else if(lamp.Green()) {
    	   Sleep();
    	   st.RD(IEType.GREEN.light());
       }else if(lamp.Yellow()) {
    	   Sleep();
    	   st.RD("Yellow");
       }
	}
	
	
	public static void Sleep() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
	
	
	
}


//---------------------------------------------------------------------------------------

package traffic;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Time {
	
	Date date = new Date();
	SimpleDateFormat Simformat = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
	private String TIME = Simformat.format(date);
	
	private static final String LOCAL = "ShilongshanStAndYunMengRd";
	private static final String DIVIDLINE = "---This is Dividing Line---";
	private static final String WORKTIME = "09";
	
	
	private static Logger logger = Logger.getLogger(Time.class.getName());


	
	public String getTime() {
		return TIME;
	}
	public String getlocal() {
		logger.log(Level.WARNING, "MastBeIn121");
		return LOCAL;
	}

	public String getDividingLine() {
		return DIVIDLINE;
	}
	
	public String getWorkTime() {
		Date nowHour = new Date();
		SimpleDateFormat nowFormat = new SimpleDateFormat("HH");
		String nowTime = nowFormat.format(nowHour);
		int NOW = Integer.valueOf(nowTime);
		int WORK = Integer.valueOf(WORKTIME);
		if(NOW>WORK) {
			return "Late";
		}else {
			return "Go";
		}
	}
	
	public String getAll() {
		try {
			return getTime() + "\n"
					+getlocal() + "\n"
					+getDividingLine() + "\n"
					+getWorkTime();
		}catch(Exception e) {
			e.printStackTrace();
		}
		throw new IllegalArgumentException("Argument Error getAll in Time");
	}
	
	
}


//---------------------------------------------------------------------------------------

package traffic;

public enum TimeStr {

	LOCAL("ShilongshanStAndYunmengRd"),
	DIVIDLINE("This is Dividing Line"),
	WORKTIME("09"),
	OTHER("---");
	
	
	private String Msg;
	
	private TimeStr(String msg) {
		this.Msg = msg;
	}

	public String getMsg() {
		return this.Msg;
	}
	
}


//---------------------------------------------------------------------------------------

package traffic;

public class TrafficLight {

	
	public static void main(String[] args) {			
		Start.Start();		
	}
}


//---------------------------------------------------------------------------------------

package traffic;



import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class TrafficLightGui extends JFrame{
	
	
	private static final long serialVersionUID = 42L;
	private JLabel lightLabel;
	private Timer timer;
	private String[] colors = {"R", "Green", "Yellow"};
	private int currentIndex = 0;
	private State s = new State();
	
	
	
	public TrafficLightGui() {
		super("R_G_Y : LIGHT: 蜈蚣山");		
		initUI();
	}
	
	
	private void initUI() {
		lightLabel = new JLabel("Wait!!!", SwingConstants.CENTER);
		lightLabel.setFont(new Font("Serif", Font.BOLD, 50));
		lightLabel.setForeground(Color.RED);//初始颜色
		add(lightLabel,BorderLayout.CENTER);
		
		setSize(500, 500);
		setLocationRelativeTo(null); //居中
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		timer = new Timer(1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("initUI初始化debug"); //--->>debug
				
				updateLight();	
						
			}			
		});
		timer.start();	
	}
	
	
	
	
	private void updateLight() {
		String colIndex = colors[(currentIndex+1) % 3];
		
		currentIndex++;
		System.out.println("循序开始:"+currentIndex+",colors:"+ colIndex );
		
		
		if(colIndex.equals("R")) {
			int Rl = IEType.RED.Seconds();
//			lightLabel.setText(IEType.RED.Description()+Rl);
			lightLabel.setText(colIndex);
			
			lightLabel.setForeground(Color.RED);
			
			
		}else if(colIndex.equals("Green")) {
			
			
			
			lightLabel.setText(IEType.GREEN.Description()+"0");
			lightLabel.setForeground(Color.GREEN);
		}else {
			lightLabel.setText(IEType.YELLOW.Description()+"0");
			lightLabel.setForeground(Color.YELLOW);
		}	
		
	}
	
	
	

	
	
	

	
	
	public static void main(String[] args) {
		
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new TrafficLightGui().setVisible(true);				
			}			
		});
		
	}
	
	
	

}


//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------























Logo

2万人民币佣金等你来拿,中德社区发起者X.Lab,联合德国优秀企业对接开发项目,领取项目得佣金!!!

更多推荐