w3resource

Java: Traffic Light Simulation

Java OOP: Exercise-8 with Solution

Write a Java program to create class called "TrafficLight" with attributes for color and duration, and methods to change the color and check for red or green.

Sample Solution:

Java Code:

//TrafficLight.java
public class TrafficLight {
  private String color;
  private int duration;

  public TrafficLight(String color, int duration) {
    this.color = color;
    this.duration = duration;
  }

  public void changeColor(String newColor) {
    color = newColor;
  }

  public boolean isRed() {
    return color.equals("red");
  }

  public boolean isGreen() {
    return color.equals("green");
  }

  public int getDuration() {
    return duration;
  }

  public void setDuration(int duration) {
    this.duration = duration;
  }
}

The above class has two private attributes: ‘color’ and ‘duration’. A constructor initializes these attributes with the values passed as arguments, and getter and setter methods to access and modify these attributes. It also has methods to change the ‘color’, and to check if the light is red or green.

//Main.java
 public class Main {
   public static void main(String[] args) {
     TrafficLight light = new TrafficLight("red", 30);

     System.out.println("The light is red: " + light.isRed());
     System.out.println("The light is green: " + light.isGreen());

     light.changeColor("green");

     System.out.println("The light is now green: " + light.isGreen());
     System.out.println("The light duration is: " + light.getDuration());
     light.setDuration(20);
     System.out.println("The light duration is now: " + light.getDuration());
   }
 }

In the above example code, we create an instance of the "TrafficLight" class with the color "red" and a duration of 30 seconds. We then print whether the light is red or green using the “isRed” and “isGreen” methods. We change the light color to "green" through the “changeColor” method, and display whether the light is now green. We also print the light duration using the “getDuration” method, and change the duration to 60 seconds with the “setDuration” method.

Sample Output:

The light is red: true
The light is green: false
The light is now green: true
The light duration is: 30
The light duration is now: 20

Flowchart:

Flowchart: Java  OOP Exercises: Traffic Light Simulation.
Flowchart: Java  OOP Exercises: Traffic Light Simulation.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java OOP Previous: Bank Account Management.
Java OOP Next: Employee class with years of service calculation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.