JAVA紅綠燈

用列舉來寫 必須讓他切換時間

設紅燈30秒黃燈5秒綠燈40秒

Update:

要用enum型別

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    public class TrafficLight extends Thread{

    Light current;

    long time;

    enum Light{

    GREEN(3), YELLOW(5), RED(30);

    public int time;

    Light(int t){

    time = t;

    }

    }

    public static void main(String[] args){

    new TrafficLight().start();

    }

    public TrafficLight(){

    current = Light.GREEN;

    time = Light.GREEN.time;

    }

    public void run(){

    while(true){

    if(time > 0){

    // 列印在螢幕上

    switch(current){

    case GREEN:

    System.out.println("綠燈" + time + "秒");

    break;

    case YELLOW:

    System.out.println("黃燈" + time + "秒");

    break;

    case RED:

    System.out.println("紅燈" + time + "秒");

    break;

    }

    // 暫停1000毫秒

    try{

    Thread.sleep(1000);

    }catch(InterruptedException e){}

    time -= 1;

    }else{

    // 更新紅綠燈號

    switch(current){

    case GREEN:

    current = Light.YELLOW;

    time = Light.YELLOW.time;

    break;

    case YELLOW:

    current = Light.RED;

    time = Light.RED.time;

    break;

    case RED:

    current = Light.GREEN;

    time = Light.GREEN.time;

    break;

    }

    }

    }

    }

    }

    方法有很多種, 提供一種給你參考

    希望這樣有幫到你

    豚仔

    Source(s):
Still have questions? Get your answers by asking now.