TryBugHunt
javaOff-by-oneEasy

A full last page adds an empty page after it

BugFind the bug and fix the code

What it should do

pageCount(items, perPage) returns how many pages are needed to show all items, so pageCount(25, 10) returns 3 and pageCount(20, 10) returns 2. No items means no pages.

What happens instead

pageCount(20, 10) returns 3 instead of 2, and pageCount(0, 10) returns 1. pageCount(25, 10) is correct.

public class Main {
    static int pageCount(int items, int perPage) {
        return items / perPage + 1;
    }
}

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 off-by-one errors pattern

The loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

What you'll practise

An easy Java debugging exercise about off-by-one errors: the loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

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)

Integer division rounds down, so items / perPage counts only the full pages. Adding 1 is a guess that there is always one partly filled page left over, which is true for 25 items but false whenever items divides evenly (20 items is exactly 2 pages) and false for 0 items. What you need is division that rounds up. For positive integers, (items + perPage - 1) / perPage does that: adding perPage - 1 pushes any remainder over the next multiple without affecting exact multiples. Math.ceil((double) items / perPage) works too. Always test a division like this with an exact multiple and with zero.

The pattern behind it: off-by-one errors.

More off-by-one errors to practise

Related errors

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/133e2352-3ff5-4639-8146-8d90934d2e7c" title="Debugging challenge: A full last page adds an empty page after it" 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/133e2352-3ff5-4639-8146-8d90934d2e7c">TryBugHunt</a></p>