TryBugHunt
javaScope errorEasy

Daily sales total always comes out as 0

BugFind the bug and fix the code

What it should do

addSale records one sale in the running total, and dailyTotal(sales) records every sale and returns the total, so dailyTotal([10, 20, 5]) returns 35.

What happens instead

dailyTotal([10, 20, 5]) returns 0.

public class Main {
    static int total = 0;

    static void addSale(int amount) {
        int total = 0;
        total += amount;
    }

    static int dailyTotal(int[] sales) {
        for (int s : sales) {
            addSale(s);
        }
        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

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)

int total = 0 inside addSale declares a new local variable that happens to have the same name as the static field. Inside that method, total now means the local, so the addition updates a variable that disappears as soon as the method returns, and the field is never touched. Java allows a local to shadow a field without any error. When you mean the field, do not redeclare it; drop the type and write total += amount, or make it explicit with Main.total. A field that never changes even though a method clearly writes to it is the typical sign of shadowing.

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/37419881-2473-48e4-b50a-308dd92dbe85" title="Debugging challenge: Daily sales total always comes out as 0" 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/37419881-2473-48e4-b50a-308dd92dbe85">TryBugHunt</a></p>