Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a class that simulates a traffic light in Java. The next method advanc

ID: 3861122 • Letter: I

Question

Implement a class that simulates a traffic light in Java. The next method advances the color in the usual way, from green to yellow to red, then again to green. Provide two constructors, as described in the documentation of the public interface. Also supply a method that yields the number of times that this traffic light has been red.

** I'm a beginner so if would be great if you make the code simple. Thanks!!

Please use the following code:

/**
A simulated traffic light.
*/
public class TrafficLight
{
private String color;
private int reds;

/**
Constructs a green traffic light.
*/
public TrafficLight()
{
. . .
}

/**
Constructs a traffic light.
@param initialColor the initial color "green", "yellow", or "red"
*/
public TrafficLight(String initialColor)
{
. . .
}

/**
Moves this traffic light to the next color.
*/
public void next()
{
. . .
}

/**
Returns the current color of this traffic light.
@return the current color
*/
public String getColor()
{
. . .
}

/**
Counts how often this traffic light has been red.
@return the number of times this traffic light has been red
*/
public int getReds()
{
. . .
}
}

Explanation / Answer

Below is your code. Let me know if you have any issue in comments...

TrafficLight.java

/**

* A simulated traffic light.

*/

public class TrafficLight {

private String color;

private int reds;

/**

* Constructs a green traffic light.

*/

public TrafficLight() {

this.color = "green";

reds = 0;

}

/**

* Constructs a traffic light.

*

* @param initialColor

* the initial color "green", "yellow", or "red"

*/

public TrafficLight(String initialColor) {

this.color = initialColor;

if (initialColor == "red") {

reds = 1;

} else {

reds = 0;

}

}

/**

* Moves this traffic light to the next color.

*/

public void next() {

// Colors must be in the order green, yellow and red and if it is red

// increment reds.

if (this.color == "green") {

this.color = "yellow";

} else if (this.color == "yellow") {

this.color = "red";

reds++;

} else if (this.color == "red") {

this.color = "green";

}

}

/**

* Returns the current color of this traffic light.

*

* @return the current color

*/

public String getColor() {

return this.color;

}

/**

* Counts how often this traffic light has been red.

*

* @return the number of times this traffic light has been red

*/

public int getReds() {

return this.reds;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote