Challenge: Weekday Switch
Task
Swipe to start coding
Write a program that takes an integer from 1
to 7
and prints the corresponding day of the week.
- Use a
switch
statement to compare the value ofday
to numbers 1-7. - For each case (1 to 7), print the corresponding day of the week.
- Add
break
after each case to prevent fall-through. - Add a
default
case to handle invalid inputs (numbers outside 1-7). In this case, print"Invalid day"
.
Note
Please note that in our system, the counting of days in the week starts on Monday. So, the first day is Monday, the second is Tuesday, and so on.
Solution
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
public class Main {
public static void printDayMessage(int day) {
switch (day) {
case 1:
System.out.println("Day of the week: Monday");
break;
case 2:
System.out.println("Day of the week: Tuesday");
break;
case 3:
System.out.println("Day of the week: Wednesday");
break;
case 4:
System.out.println("Day of the week: Thursday");
break;
case 5:
System.out.println("Day of the week: Friday");
break;
case 6:
System.out.println("Day of the week: Saturday");
break;
case 7:
System.out.println("Day of the week: Sunday");
break;
default:
System.out.println("Invalid day");
}
}
public static void main(String[] args) {
int day = 4;
printDayMessage(day);
}
}
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 8
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
public class Main {
public static void printDayMessage(int day) {
switch (day) {
case 1:
System.out.println("Day of the week: " + ___);
___;
case 2:
System.out.println("Day of the week: " + ___);
___;
case 3:
System.out.println("Day of the week: " + ___);
___;
case 4:
System.out.println("Day of the week: " + ___);
___;
case 5:
System.out.println("Day of the week: " + ___);
___;
case 6:
System.out.println("Day of the week: " + ___);
___;
case 7:
System.out.println("Day of the week: " + ___);
___;
default:
System.out.println("Day of the week: " + ___);
___;
}
}
public static void main(String[] args) {
int day = 4;
printDayMessage(day);
Ask AI
Ask anything or try one of the suggested questions to begin our chat