【发布时间】:2016-01-08 12:56:46
【问题描述】:
我基本上必须编写一个交通信号灯,从红色开始,然后从红色变为绿色,然后再次变为红色。我设法让红绿灯从红色闪烁变为绿色,但反之亦然,有人可以看看我的代码,看看我在 if 和 else 语句上做错了什么。
/** * Write a description of class TrafficLight here. * *
@author (your name) * @version (a version number or a date) */
public class TrafficLight {
// instance variables - replace the example below with your own
private Circle red;
private Circle yellow;
private Circle green;
private Boolean stop;
/**
* Constructor for objects of class TrafficLight
*/
public TrafficLight()
{
red = new Circle();
red.changeColor("red");
red.moveHorizontal(200);
red.moveVertical(200);
red.changeSize(60);
red.makeVisible();
stop=true;
stop=false;
yellow = new Circle();
yellow.changeColor("black");
yellow.moveHorizontal(200);
yellow.moveVertical(260);
yellow.changeSize(60);
yellow.makeVisible();
green = new Circle();
green.changeColor("black");
green.moveHorizontal(200);
green.moveVertical(320);
green.changeSize(60);
green.makeVisible();
// Construct the circles
// Set their color and make them visible
// Set stop to be true;
}
/**
* If the traffic light shows STOP, it changes to GO.
* If the traffic light shows GO, it changes to STOP.
*/
public void change() {
// read the instructions for the user story
// of how this method should work
if (stop==false) {
red.changeColor("red");
yellow.changeColor("yellow");
green.changeColor("black");
pause();
red.changeColor("black");
yellow.changeColor("black");
green.changeColor("green");
pause();
} else{
red.changeColor("black");
yellow.changeColor("yellow");
green.changeColor("black");
pause();
red.changeColor("red");
yellow.changeColor("black");
green.changeColor("black");
}
/*
* Do not change anything in the pause method
*/
}
private void pause() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
}
【问题讨论】:
-
停止值始终设置为 false。这就是问题所在。我可以看到您将 stop 初始化为 true 并再次为 false。尝试更改它并以适当的方式对其进行初始化。
-
@ShiladittyaChakraborty 你是什么意思?我应该如何改变它?
-
if (stop==false) then set stop = true 反之亦然
-
@ShiladittyaChakraborty 它不工作
-
检查我的答案。让我知道它是否对您有帮助。
标签: java if-statement bluej statements