import java.util.InputMismatchException;
import java.util.Scanner;
public class GuessingGame {
public static void main(String args) {
playGame();
}
public static void playGame() {
System.out.println("Welcome to the Guessing Game!");
System.out.println("Guess a number between 1 and 100.");
int minValue = 1;
int maxValue = 100;
int guessAmount = 1;
int maxAttempts = 5;
int randomNumber = generateRandomNumber(minValue, maxValue);
System.out.println(randomNumber);
inputValidation(minValue, maxValue, guessAmount, maxAttempts, randomNumber);
}
public static int generateRandomNumber(int minValue, int maxValue) {
return (int) Math.round(Math.random() * 100);
}
public static void inputValidation(int minValue, int maxValue, int guessAmount, int maxAttempts, int randomNumber) {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
int guessNumber = getGuessNumber(minValue, maxValue, scanner);
if (guessNumber != randomNumber)
provideHint(guessNumber, randomNumber);
else if (guessAmount > maxAttempts) {
System.out.println("Time out!");
break;
} else {
System.out.println("Correct!");
System.out.println("You guessed " + guessAmount + " times");
break;
}
} catch (InputMismatchException e) {
System.out.println("Please select a valid integer");
}
guessAmount++;
}
}
public static int getGuessNumber(int minValue, int maxValue, Scanner scanner) {
System.out.print("Guess a number from " + minValue + " to " + maxValue + ": ");
return scanner.nextInt();
}
public static void provideHint(int guessNumber, int randomNumber) {
if (guessNumber > randomNumber) {
System.out.println("Try again! Your guess is too high");
} else {
System.out.println("Try again! Your guess is too low");
}
}
}