πΉ Introduction
In Java programming, decision-making statements play a crucial role in controlling the flow of execution. One such statement is the switch case, which is used when we need to execute different code blocks based on a single value.
In this blog, we will learn how to write a Java program to display the day of the week based on a number entered by the user using a switch case.
πΉ Problem Statement
Write a Java program that:
β’ Takes a number from 1 to 7 as input
β’ Displays the corresponding day of the week
Mapping:
β’ 1 β Monday
β’ 2 β Tuesday
β’ 3 β Wednesday
β’ 4 β Thursday
β’ 5 β Friday
β’ 6 β Saturday
β’ 7 β Sunday
If the user enters any other number, the program should display an invalid input message.
πΉ Why Use Switch Case?
β’ It improves readability when handling multiple conditions
β’ It is more structured and cleaner than multiple if-else statements
β’ Best suited when comparing a single variable with fixed values
πΉ Java Program: Day of the Week Using Switch Case
import java.util.Scanner;
public class DayOfWeek {
public static void main(String[] args) {
System.out.println("Enter a number(1-7):");
Scanner scan = new Scanner(System.in);
int day = scan.nextInt();
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid input");
}
}
}
πΉ Sample Input and Output
Input:
Enter a number (1-7): 3
Output:
Wednesday
πΉ Explanation
β’ Scanner class is used to get input from the user
β’ The switch statement checks the value of day
β’ Each case represents a day of the week
β’ break stops execution after the matched case
β’ default handles invalid inputs
Top comments (0)