写一段红绿灯JAVA代码
以下是一个简单的红绿灯Java代码,模拟一个红绿灯交通信号控制器的功能:
public class TrafficLightController {
public static void main(String[] args) {
int redTime = 10; // 红灯时间
int greenTime = 15; // 绿灯时间
int yellowTime = 3; // 黄灯时间
String currentLight = "green"; // 当前信号灯的颜色
// 无限循环模拟交通信号灯的变化
while (true) {
switch (currentLight) {
case "green":
System.out.println("绿灯亮起,可以通行");
try {
Thread.sleep(greenTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentLight = "yellow";
break;
case "yellow":
System.out.println("黄灯亮起,请注意慢行");
try {
Thread.sleep(yellowTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentLight = "red";
break;
case "red":
System.out.println("红灯亮起,请停车等待");
try {
Thread.sleep(redTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentLight = "green";
break;
default:
break;
}
}
}
}
在以上代码中,我们使用了一个 while 循环来模拟交通信号灯的变化。变量 redTime、greenTime 和 yellowTime 分别表示红灯、绿灯和黄灯的持续时间,单位为秒。变量 currentLight 初始值为绿灯,然后在不断地循环中根据不同的灯光状态进行切换。
在 switch 语句中,根据当前灯光状态进行不同的操作。当绿灯亮起时,输出“绿灯亮起,可以通行”,然后等待 greenTime 秒钟后将当前灯光状态切换为黄灯;当黄灯亮起时,输出“黄灯亮起,请注意慢行”,然后等待 yellowTime 秒钟后将当前灯光状态切换为红灯;当红灯亮起时,输出“红灯亮起,请停车等待”,然后等待 redTime 秒钟后将当前灯光状态切换为绿灯。
该代码可以不断地重复执行,模拟交通信号灯的循环变化。
原文地址: http://www.cveoy.top/t/topic/bLE0 著作权归作者所有。请勿转载和采集!