AI Hints
Home›Java Tutorial›Switch Expressions, Nested Decisions, Practice: Grade Checker
Java · Lesson 36 of 120

Practice: Grade Checker

Put module four together.

⏱ 2 min read▶ Video at 45:59🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module four together. Read a score, and print a grade. And handle scores that don't make sense.

  • Read a score
  • Print a grade
  • Catch bad input

A grade checker

Your turn. Pause the video, and try this. Read a score, from zero to a hundred. Print grade A for ninety or more, B for seventy five or more, C for fifty or more, and F below that. If the score is outside zero to a hundred, say so. Here is one solution. The invalid check comes first, using or. Then the grades go from highest to lowest, so the first true one wins. Eighty two is a B.

✍️ Exercise: A grade checker

Read a score. 90+ → A, 75+ → B, 50+ → C, else F. Outside 0–100 → "not a valid score".

Show hint

check score < 0 || score > 100 first

Show solution
Main.javajava
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Score (0-100): ");
        int score = in.nextInt();
        if (score < 0 || score > 100) {
            System.out.println("That's not a valid score.");
        } else if (score >= 90) {
            System.out.println("Grade A");
        } else if (score >= 75) {
            System.out.println("Grade B");
        } else if (score >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Grade F");
        }
    }
}
Output
Score (0-100): 82
Grade B

What module four taught

Comparisons give true or false. If, else, and else if choose a path. And, or, and not combine conditions. The ternary operator picks one of two values. And switch chooses between many cases.

keyvalue
Compare== != < > <= >=
Chooseif, else if, else
Combine&& || !
Many casesswitch ->

Summary

Your programs can now make decisions. That's the end of module four. Next module, loops.

Key takeaways
  • Conditions
  • if / else
  • switch
Next up: while Loops — repeat while true