Codiqo

Learn Java · lesson 17 of 61 · about 9 minutes

Project: The Final Bill

The visit ends with a bill. Add it up, give the customer a loyalty tier with else if, and pick the thank-you message with a switch expression.

What you'll learn

  • Rank a total with else if, highest band first
  • Test every band at its edge
  • Pick a message with a switch expression

The plan

1. The bill is groupTotal + snackCents, and each whole dollar earns a point
2. The tier is Gold from 100 points, Silver from 50, Bronze from 20, and None below that
3. Print the bill, the points and the tier
4. Pick the thank-you with a switch expression: Gold gets a free ticket, Silver and Bronze share one message, and anything else gets See you soon.

Check the bands from the top. Only the first true branch runs, so each else if only needs its lower edge.

Finding the tier

public class Main {
    public static void main(String[] args) {
        int bill = 5063;
        int points = bill / 100;
        String tier;
        if (points >= 100) {
            tier = "Gold";
        } else if (points >= 50) {
            tier = "Silver";
        } else {
            tier = "None";
        }
        System.out.println(points + " points: " + tier);
    }
}

Output

50 points: Silver

Every path needs a value

String tier; creates the variable without a value, and Java checks that every path through the if gives it one before it's used. Leave out the last else, and some totals would reach the println with no tier at all, so the program doesn't compile: variable tier might not have been initialized.

Test every edge

Each band starts at an exact number of points, so test those first: 100, 50 and 20, then a total just below each one. A tier that's wrong at its edge is the most common bug in code like this.

Now try it yourself

This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.