TryBugHunt
javaType errorEasy

Product rating of 4.5 shows as 4.0

BugFind the bug and fix the code

What it should do

averageRating(ratings) returns the mean of a non-empty list of star ratings, so averageRating([4, 5]) returns 4.5.

What happens instead

averageRating([4, 5]) returns 4.0 instead of 4.5.

import java.util.*;

public class Main {
    static double averageRating(List<Integer> ratings) {
        int sum = 0;
        for (int r : ratings) {
            sum += r;
        }
        return sum / ratings.size();
    }
}

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 type errors pattern

Integer division, autoboxing surprises, and == comparing references instead of values.

What you'll practise

An easy Java debugging exercise about type errors: integer division, autoboxing surprises, and == comparing references instead of values.

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)

sum is an int and ratings.size() is an int, so sum / ratings.size() is integer division: 9 / 2 is 4. Java converts that 4 to 4.0 when it returns, but the half is already gone. Casting one operand to double before dividing, (double) sum / ratings.size(), makes Java do floating-point division. Be careful where the cast goes: (double) (sum / ratings.size()) casts after the integer division and still gives 4.0. Averages whose true value is a whole number hide the bug, so always include a test whose average has a fraction.

The pattern behind it: type errors.

More type 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/9649a5d0-5372-4bac-8fe6-bbb0503823a1" title="Debugging challenge: Product rating of 4.5 shows as 4.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/9649a5d0-5372-4bac-8fe6-bbb0503823a1">TryBugHunt</a></p>