Weekday or Weekend (Switch Expression)
Problem
Read the name of a day (any letter case). Print Weekday for Monday to Friday, Weekend for Saturday and Sunday, and Invalid for anything else.
Constraints
- The input is one word
Examples
Input
Saturday
Output
Weekend
Solutions
A switch chooses one result from many labels. The old Java style needs break statements, and forgetting one is a classic bug.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : Weekday, Weekend or Invalid.
* Approach: Switch on the day.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String s) {
// Step 1: Make the day lower case, so Monday, MONDAY and monday are the same.
String day = s.trim().toLowerCase();
// Step 2: Old style switch statement. Every case needs a break, or the next case also runs.
String result;
switch (day) {
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
result = "Weekday";
break;
case "saturday":
case "sunday":
result = "Weekend";
break;
default:
result = "Invalid";
break;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Which cases have the same result?