πΉ Introduction
In real-world applications, traffic light systems are used to control the flow of vehicles and ensure road safety. In Java, such logic can be implemented using decision-making statements. One of the most suitable statements for this purpose is the switch case, which allows us to execute different actions based on a single input.
In this blog, we will create a Java program that displays the correct action based on the traffic light color.
πΉ Problem Statement
Write a Java program that:
β’ Accepts a traffic light color as input (red, yellow, or green)
β’ Displays the corresponding action
Rules:
β’ Red β Stop
β’ Yellow β Ready
β’ Green β Go
If the user enters any other value, the program should display an invalid color message.
πΉ Java Program: Traffic Light System Using Switch Case
import java.util.Scanner;
public class TrafficLightSystem {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter traffic light color:");
String color=scan.nextLine();
switch(color) {
case "red":
System.out.println("Stop");
break;
case "yellow":
System.out.println("Ready");
break;
case "green":
System.out.println("Go");
break;
default:
System.out.println("Invalid color");
}
}
}
πΉ Sample Input and Output
Input:
Enter traffic light color : green
Output:
Go
Top comments (0)