Java Program to print DAY according to user input for day count.
Objective
Write a Java program to display the name of the day corresponding to a given number (1-7) using a switch statement.
Algorithm / Approach
- Prompt the user to enter an integer between 1 and 7.
- Pass the input integer into a
switchstatement. - Provide a
caseblock for each day (1 = Monday, 2 = Tuesday, etc.). - Inside each case, print the day and use the
breakkeyword. - Add a
defaultblock to handle inputs outside the 1-7 range.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Day Number: ");
int x = s.nextInt();
switch(x) {
case 1:
System.out.print("DAY IS MONDAY");
break;
case 2:
System.out.print("DAY IS TUESDAY");
break;
case 3:
System.out.print("DAY IS WEDNESDAY");
break;
case 4:
System.out.print("DAY IS THURSDAY");
break;
case 5:
System.out.print("DAY IS FRIDAY");
break;
case 6:
System.out.print("DAY IS SATURDAY");
break;
case 7:
System.out.print("DAY IS SUNDAY");
break;
default:
System.out.print("Wrong Choice");
}
}
}
Expected Output
Enter Day Number 4 DAY IS THURSDAY
Explanation of the Program
- A
switchstatement is a cleaner alternative to a longif-else ifladder when comparing a single variable against exact constant values. - The
breakstatement forces the program to exit the switch block once a match is found and executed. - Without the
breakstatement, execution would "fall through" and print the subsequent days as well. - The
defaultcase acts like a finalelse, catching invalid inputs.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Forgetting the
breakkeyword at the end of each case block. - Using ranges or logical operators (like
>or&&) inside case labels, which is not allowed in standard Java switch statements.