Java: Days of the week as an enum

An enum gives a fixed set of values names, an order and methods.

What to build

A program that describes each day of the week it reads.

Requirements

  • Write enum Day with the seven days from MONDAY to SUNDAY and a method isWeekend() (Saturday and Sunday).
  • For each word, ignoring case, print DAY: day N, weekend or DAY: day N, weekday, where DAY is the constant's name and N its position from 1; print no such day WORD for anything else.

Input

Line 1: n. Then n words.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

3
monday
Saturday
funday

Output:

MONDAY: day 1, weekday
SATURDAY: day 6, weekend
no such day funday

Why it works

valueOf turns text into a constant or refuses it, ordinal gives the position, and the weekend rule lives in the enum itself.

Examples

Example 1 · Input
3
monday
Saturday
funday
Expected output
MONDAY: day 1, weekday
SATURDAY: day 6, weekend
no such day funday
Example 2 · Input
1
SUNDAY
Expected output
SUNDAY: day 7, weekend

Hints

Hint 1

enum Day { MONDAY, ..., SUNDAY } with a method isWeekend().

Hint 2

Day.valueOf(word.toUpperCase()) throws IllegalArgumentException for an unknown word: catch it.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

    boolean isWeekend() {
        return this == SATURDAY || this == SUNDAY;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            String word = in.next();
            try {
                Day d = Day.valueOf(word.toUpperCase());
                System.out.println(d + ": day " + (d.ordinal() + 1) + ", " + (d.isWeekend() ? "weekend" : "weekday"));
            } catch (IllegalArgumentException e) {
                System.out.println("no such day " + word);
            }
        }
    }
}

Lesson: Interfaces, enums and records →