首先,我对Java很陌生。在大学时,我们使用raspberry pi 3和Java NetBeans进行编程。
我必须制作红绿灯。交通信号灯应在正常模式下工作2分30秒。然后它应该切换到闪烁的黄灯,应该工作1分钟,之后它应该关闭。在正常模式下,每个灯都没有特定的时间。我必须在上面写的那些时间框架中编写这段代码:
// Normal mode for 2 minutes 30 seconds
red.on();
Thread.sleep(1000);
red.off();
Thread.sleep(100);
yellow.on();
Thread.sleep(1000);
yellow.off();
Thread.sleep(1000);
green.on();
Thread.sleep(1000);
green.off();
Thread.sleep(1000);
// Only yellow blinking for 1 minute
yellow.on();
Thread.sleep(1000);
yellow.off();
Thread.sleep(1000);
//Shutdown after 1 minute of yellow blinking
red.off();
yellow.off();
green.off();
如何将这些模式放在这些时间范围内?我认为我可以使用for
循环但不知道如何设置正确的时间,也许任何其他选项或任何人都可以使用for
循环进行此操作?
对不起,如果有些句子错了,因为英语不是我的第一语言。
答案 0 :(得分:0)
您可以使用while循环。
// Normal mode for 2 minutes 30 seconds
int pauseTime = 1000
int normalElapsedTime = 0
int blinkingElapsedTime = 0
while (normalElapsedTime < (60000*2.5))
{
red.on();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
red.off();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
yellow.on();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
yellow.off();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
green.on();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
green.off();
Thread.sleep(pauseTime);
normalElapsedTime = normalElapsedTime + pauseTime;
} //end while
// Only yellow blinking for 1 minute
while (blinkingElapsedTime < (60000*1))
{
yellow.on();
Thread.sleep(pauseTime);
blinkingElapsedTime = blinkingElapsedTime + pauseTime;
yellow.off();
Thread.sleep(pauseTime);
blinkingElapsedTime = blinkingElapsedTime + pauseTime;
} //end while
//Shutdown after 1 minute of yellow blinking
red.off();
yellow.off();
green.off();