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.