TryBugHunt
javaScope errorMedium

Checkout ignores the tax rate it is given

BugFind the bug and fix the code

What it should do

The shop's default tax is 8 percent, but checkout(prices, taxPercent) must use the rate it is given for this order. So checkout([100, 200], 10) returns 330 (prices in cents).

What happens instead

checkout([100, 200], 10) returns 324, which is the 8 percent default, and checkout([1000], 0) returns 1080.

public class Main {
    static int taxPercent = 8;

    static int withTax(int cents) {
        return cents + cents * taxPercent / 100;
    }

    static int checkout(int[] prices, int taxPercent) {
        int total = 0;
        for (int p : prices) {
            total += withTax(p);
        }
        return total;
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the scope and closure bugs pattern

A field shadowed by a local or parameter with the same name, so the field never changes.

What you'll practise

A medium Java debugging exercise about scope and closure bugs: a field shadowed by a local or parameter with the same name, so the field never changes.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

checkout's parameter taxPercent shadows the static field only inside checkout. withTax is a different method, and inside it the name taxPercent can only mean the field, which is still 8. Local variables and parameters are visible only in the method that declares them; calling another method does not pass them along. Having a parameter with the same name as a field makes the code look connected when it is not. Pass the value explicitly as an argument, as the fix does. When a value seems to be ignored, check which declaration each use of the name actually refers to.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/9b041148-0f33-44ba-a70e-42775253dc76" title="Debugging challenge: Checkout ignores the tax rate it is given" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/9b041148-0f33-44ba-a70e-42775253dc76">TryBugHunt</a></p>