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

Solução ao jogo de adivinhação | Poderiam analisar?

Achei divertido este desafio, pude por em pratica conceitos que conhece nos vídeo do Tio Akita para melhor legibilidade de código e também o que aprendi durante a formação básica do curso. Comecei criando um único método chamado gameManager e escrevi toda funcionalidade do jogo nele, após isso, fui separando/tirando partes do código e passando para métodos próprio ou auxiliares e depois englobei tudo no método principal e no fim este foi o resultado:

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

        gameManager(sc, 1, 100);

        sc.close();
    }

    /**
     * Generates a random number within a specified range.
     * @param min Minimum value.
     * @param max Maximum value.
     * @return Random number between min and max (inclusive).
     */
    private static int randomNumber(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    /**
     * Manages the game logic, handling attempts and checking correctness.
     * @param scanner Scanner for user input.
     * @param min Minimum value for the secret number.
     * @param max Maximum value for the secret number.
     */
    private static void gameManager(Scanner scanner, int min, int max) {
        int attempts = 1;
        int secretNumber = randomNumber(min, max);

        while (attempts <= 5) {
            System.out.printf("Enter a number between %d and %d: ", min, max);
            int choice = scanner.nextInt();

            if (choice != secretNumber) {
                System.out.println(tryAgain(choice, secretNumber));
                attempts++;
            } else {
                System.out.printf(
                        "Congratulations, you got it right! The secret number is %d. You guessed it in %d %s.\n",
                        secretNumber, attempts, attemptLabel(attempts)
                );
                return;
            }
        }

        System.out.printf("Game over! The secret number was %d.\n", secretNumber);
    }

    /**
     * Returns a hint for the player based on the chosen number.
     * @param choice Number chosen by the player.
     * @param secretNumber The secret number to be guessed.
     * @return String indicating whether the secret number is higher or lower.
     */
    private static String tryAgain(int choice, int secretNumber) {
        return choice < secretNumber ? "The secret number is higher." : "The secret number is lower.";
    }

    /**
     * Returns the word "attempt" in singular or plural depending on the count.
     * @param attempts Number of attempts.
     * @return "attempts" for more than one, "attempt" for just one.
     */
    private static String attemptLabel(int attempts) {
        return attempts > 1 ? "attempts" : "attempt";
    }
}

Não sei se atende corretamente o desafio proposto, mas achei divertido faze-lo mesmo assim.

1 resposta
solução!

Olá, Rick. Tudo bem?

Obrigado por compartilhar seu código com a gente.

Muito bom como você organizou o código separando as responsabilidades em métodos auxiliares. Isso melhora a legibilidade e facilita futuras manutenções.

Uma dica e curiosidade: você pode utilizar um laço do-while para garantir que pelo menos uma tentativa seja feita antes de verificar a condição de saída. Veja este exemplo:


do {
    System.out.printf("Enter a number between %d and %d: ", min, max);
    choice = scanner.nextInt();
    System.out.println(tryAgain(choice, secretNumber));
    attempts++;
} while (choice != secretNumber && attempts <= 5);

Isso garante que o usuário sempre tenha pelo menos uma tentativa antes do fim do jogo. Parabéns pelo ótimo trabalho. O código está correto e atende o esperado.

Conte com o apoio do Fórum. Abraços e bons estudos.