TryBugHunt
javaInfinite loopEasy

Space counter hangs on normal sentences

BugFind the bug and fix the code

What it should do

countSpaces(text) counts the space characters in text, so countSpaces("a b c") returns 2.

What happens instead

countSpaces("a b c") never returns and the run times out. countSpaces(" ") correctly returns 3.

public class Main {
    static int countSpaces(String text) {
        int count = 0;
        int i = 0;
        while (i < text.length()) {
            if (text.charAt(i) == ' ') {
                count++;
                i++;
            }
        }
        return count;
    }
}

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 infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

An easy Java debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

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 loop only moves forward when the current character is a space, because i++ sits inside the if. As soon as it meets any other character, i stops changing, the condition i < text.length() stays true, and the loop checks the same letter forever. A string made only of spaces hides the bug. In a while loop, the step that moves towards the end should normally happen on every path through the body. A for loop puts the step in the header, for (int i = 0; i < n; i++), which makes this mistake much harder to make.

The pattern behind it: infinite loops.

More infinite loops 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/b21a185c-a224-4c83-a835-608ebc2b4928" title="Debugging challenge: Space counter hangs on normal sentences" 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/b21a185c-a224-4c83-a835-608ebc2b4928">TryBugHunt</a></p>