Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

[Sugestão] Usando Enum & Supplier<T> para validação do dia da semana

Fiz este desafio simples e, por mais básico que seja, ele me proporcionou aplicar algo que eu havia visto apenas vagamente em outros projetos. Refiro-me ao Supplier<T>. O Supplier basicamente gera ou devolve um valor de forma atrasada (lazy), e além disso, não há necessidade de passar nenhum argumento inicial para ele — ele simplesmente retorna algo quando o método get() é chamado.

Verificação de dia útil
Este foi o resultado do desafio:

package org.maelys;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Locale;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * Enum representing the days of the week.
 * Each constant is associated with a lowercase string representation (e.g., "monday").
 *
 * <p>Provides utility methods for checking if a string matches a day of the week,
 * converting strings to enum values, and displaying results using a {@link Supplier}.
 */
@lombok.ToString(of = "weekDay")
@lombok.Getter(value = lombok.AccessLevel.PRIVATE)
@lombok.RequiredArgsConstructor(access = lombok.AccessLevel.PRIVATE)
public enum Week {

    /* ========================== Enum Constants ============================ */

    MONDAY("monday"),
    TUESDAY("tuesday"),
    WEDNESDAY("wednesday"),
    THURSDAY("thursday"),
    FRIDAY("friday"),
    SATURDAY("saturday"),
    SUNDAY("sunday");

    /* ============================== Field ================================= */

    /** Lowercase string representation of the day. */
    private final String weekDay;

    /* ========================== Display Method ============================ */

    /**
     * Displays the result provided by the {@link Supplier}. 
     * If the result is null, prints "Invalid day" instead.
     *
     * @param args a supplier that provides the string to display.
     */
    public static void display(@NotNull Supplier<String> args) {
        String result = args.get();
        if (result == null) result = "Invalid day";
        System.out.println(result);
    }

    /* ========================= Utility Methods ============================ */

    /**
     * Attempts to find a {@code Week} enum value that matches the input string.
     *
     * @param args the input string representing a day (case-insensitive).
     * @return an {@link Optional} containing the corresponding {@code Week}, or empty if not found.
     */
    public static @NotNull Optional<Week> getDay(@NotNull String args) {
        return Optional.ofNullable(fromString(args));
    }

    /**
     * Checks whether the given string corresponds to a valid day of the week.
     *
     * @param args the input string (case-insensitive).
     * @return {@code true} if the string matches a valid day, otherwise {@code false}.
     */
    @Contract(pure = true)
    public static boolean isWeekDay(@NotNull String args) {
        return fromString(args) != null;
    }

    /**
     * Converts a string to the corresponding {@code Week} enum constant.
     * The comparison is case-insensitive and expects full names (e.g., "monday").
     *
     * @param args the string to convert.
     * @return the matching {@code Week} enum, or {@code null} if not matched or blank.
     */
    @Contract(pure = true)
    public static @Nullable Week fromString(@NotNull String args) {
        if (args.isBlank()) return null;

        return switch (args.toLowerCase(Locale.US)) {
            case "monday" -> MONDAY;
            case "tuesday" -> TUESDAY;
            case "wednesday" -> WEDNESDAY;
            case "thursday" -> THURSDAY;
            case "friday" -> FRIDAY;
            case "saturday" -> SATURDAY;
            case "sunday" -> SUNDAY;
            default -> null;
        };
    }
}

Class Main

package org.maelys;

import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

        Week.display(() -> {
            System.out.println("Enter a day of the week:");
            String input = scanner.nextLine().toLowerCase(Locale.US);
            return Week.isWeekDay(input) ? String.format("Day of the week is %s", input) : "Invalid day";
        });
        scanner.close();
    }
}
1 resposta
solução!

Oi Rick, como vai?

Após uma análise mais profunda, conclui que seu código está correto, funcional e demonstra um bom uso do Supplier.
As sugestões abaixo são 100% opcionais e voltadas para possíveis melhorias ou escalabilidade, mas o código está atendendo perfeitamente ao desafio. Parabéns pelo ótimo trabalho!

Boas Práticas (que eu acho que você mandou muito bem):
O uso do Optional em getDay é uma excelente escolha para evitar NullPointerException.
O código é modular, com responsabilidades bem separadas entre os métodos.

Possíveis Melhorias:
Você poderia adicionar uma verificação adicional para entradas em branco diretamente no Main antes de chamar Week.display, embora o método fromString já trate isso retornando null.

O método fromString poderia ser otimizado usando um Map ou Enum.valueOf para evitar o switch, especialmente se o número de dias fosse maior. No entanto, para sete dias, o switch é perfeitamente aceitável e legível.

Belíssimo código! Bons estudos.