// Computes a student's average and letter grade from scores entered one at a time.

/// Asks until the user enters a whole number from 0 to 100, and returns it.
/// Returns -1 if input ends first.
int getScore(String prompt) {
    while (true) {
        String answer = IO.readln(prompt);
        if (answer == null) {
            break;
        }

        try {
            int score = Integer.parseInt(answer.strip());
            if (score >= 0 && score <= 100) {
                return score;
            }
        } catch (NumberFormatException e) {
            // Not a whole number: the message below says so.
        }
        IO.println("Please enter a whole number from 0 to 100.");
    }
    return -1;
}

/// Returns the letter grade for a numeric average.
String letterGrade(double average) {
    if (average >= 90) {
        return "A";
    } else if (average >= 80) {
        return "B";
    } else if (average >= 70) {
        return "C";
    } else if (average >= 60) {
        return "D";
    } else {
        return "F";
    }
}

/// Displays a formatted grade report.
void printReport(String name, double average, String grade) {
    IO.println();
    IO.println("=".repeat(32));
    IO.println("Student: " + name);
    IO.println("Average: " + String.format("%.1f", average));
    IO.println("Grade:   " + grade);
    IO.println("=".repeat(32));
}

/// Runs the grade calculator.
void main() {
    String name = IO.readln("Student name: ");

    int total = 0;
    int count = 4;
    for (int i = 0; i < count; i++) {
        int score = getScore("Score " + (i + 1) + " of " + count + ": ");
        if (score == -1) {
            return;
        }
        total += score;
    }

    double average = (double) total / count;
    printReport(name, average, letterGrade(average));
}

// From Groundwork, chapter 6 (ch06-methods), box 23.
// This example is from Groundwork, licensed CC BY-NC-SA 4.0.
// Run with: java ch06_23.java
