TryBugHunt
javaScope errorEasy

Discount setting never changes the price

BugFind the bug and fix the code

What it should do

setDiscount stores a discount percentage, and finalPrice(price, percent) sets it and returns the discounted price, so finalPrice(200, 10) returns 180.

What happens instead

finalPrice(200, 10) returns 200, as if there were no discount.

public class Main {
    static int discount = 0;

    static void setDiscount(int discount) {
        discount = discount;
    }

    static int finalPrice(int price, int percent) {
        setDiscount(percent);
        return price - price * discount / 100;
    }
}

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

An easy 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)

Inside setDiscount, the parameter is called discount, the same name as the static field. A parameter shadows the field, so both sides of discount = discount refer to the parameter, and the line assigns the parameter to itself. The field keeps its starting value of 0. In an instance method you would write this.discount = discount; in a static method there is no this, so use the class name: Main.discount = discount. Giving parameters a different name, such as newDiscount, avoids the problem entirely. Most IDEs warn that the assignment has no effect.

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/6fb93352-e460-406e-aa21-40d032eae92e" title="Debugging challenge: Discount setting never changes the price" 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/6fb93352-e460-406e-aa21-40d032eae92e">TryBugHunt</a></p>