TryBugHunt
javaLogic errorHard

One hour thirty minutes parses as 190 minutes

BugFind the bug and fix the code

What it should do

parseDuration(text) converts a duration like "1h30m" into minutes, so parseDuration("1h30m") returns 90, parseDuration("45m") returns 45 and parseDuration("2h") returns 120.

What happens instead

parseDuration("1h30m") returns 190 instead of 90. "45m" and "2h" on their own are correct.

public class Main {
    static int parseDuration(String text) {
        int total = 0;
        int num = 0;
        for (char c : text.toCharArray()) {
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c == 'h') {
                total += num * 60;
            } else if (c == 'm') {
                total += num;
                num = 0;
            }
        }
        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 logic errors pattern

The wrong operator, an inverted condition, a formula the right way round but backwards.

What you'll practise

A hard Java debugging exercise about logic errors: the wrong operator, an inverted condition, a formula the right way round but backwards.

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)

The parser builds a number digit by digit in num and, when it reaches a unit letter, adds that number to the total. After using num it has to start the next number from 0. The m branch does that, but the h branch does not, so the 1 from "1h" stays in num and the next digits are appended to it: 1, then 13, then 130. That is how 60 + 130 gives 190. Any time you accumulate a value and then consume it, reset it in every branch that consumes it. Inputs with only one unit hide the bug, so test combinations.

The pattern behind it: logic errors.

More logic errors 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/c9242b69-e44f-440a-9418-881137d1cc22" title="Debugging challenge: One hour thirty minutes parses as 190 minutes" 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/c9242b69-e44f-440a-9418-881137d1cc22">TryBugHunt</a></p>