Day of the Week
Problem
Read a number from 1 to 7 and print the name of the day: 1 is Monday, 2 is Tuesday, and so on until 7 is Sunday. For any other number print Invalid day.
Constraints
- -1000 <= n <= 1000
Examples
Input
3
Output
Wednesday
Solutions
A switch compares one value with many cases. Python has no switch in version 3.8, so a dictionary with a default value does the same job.
/*
* Problem : Print the day name for a day number.
* Input : One integer.
* Output : The day name or Invalid day.
* Approach: Choose with a switch statement.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int day = new Scanner(System.in).nextInt();
// Step 1: A switch statement picks the case that has the same value as "day".
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;
// Step 2: default runs when no case matches.
default: System.out.println("Invalid day");
}
}
}
Hints (1)
- What do you want to happen when no case matches?