// A guessing game with a limited number of tries.

void main() {
    Random random = new Random();
    int secret = random.nextInt(100) + 1;
    int maxTries = 7;
    int triesUsed = 0;
    boolean won = false;

    IO.println("I am thinking of a number between 1 and 100.");
    IO.println("You have " + maxTries + " tries.");
    IO.println();

    while (triesUsed < maxTries) {
        String guessText = IO.readln("Try " + (triesUsed + 1) + ": ");
        if (guessText == null) {
            break;
        }

        int guess;
        try {
            guess = Integer.parseInt(guessText.strip());
        } catch (NumberFormatException e) {
            IO.println("Please enter a whole number.");
            continue;
        }
        if (guess < 1 || guess > 100) {
            IO.println("Please guess from 1 to 100.");
            continue;
        }

        triesUsed++;

        if (guess == secret) {
            won = true;
            break;
        } else if (guess < secret) {
            IO.println("Too low.");
        } else {
            IO.println("Too high.");
        }
    }

    IO.println();
    if (won) {
        IO.println("Correct. You got it in " + triesUsed + " tries.");
    } else {
        IO.println("Out of tries. The number was " + secret + ".");
    }
}

// From Groundwork, chapter 5 (ch05-repetition), box 22.
// This example is from Groundwork, licensed CC BY-NC-SA 4.0.
// Run with: java ch05_22.java
