Hi,

Why does this piece of code throw me an error saying: cannot return a value from method whose result type is void?

public void orderTotal()
       {
       int total;

       for (Order filename: Orders) {

         total = filename.getQuantity(); 


        }

        return total;
   }

Dani AI

Generated

correctly pointed to the root cause: the method was declared with no return type while a return statement tries to return a value. The declaration must match what is returned (for example int), or the return statement must be removed. Also be sure the local total is definitely assigned on every path (initialize it) so the compiler won't complain when the loop never runs.

A common, robust pattern for summing quantities looks like this:

public int calculateOrderTotal(List<Order> orders) {
    int total = 0;
    if (orders == null) return 0;
    for (Order order : orders) {
        if (order != null) total += order.getQuantity();
    }
    return total;
}

For a more concise, modern style (and to skip null entries):

int total = (orders == null) ? 0 :
    orders.stream()
          .filter(Objects::nonNull)
          .mapToInt(Order::getQuantity)
          .sum();

A few practical notes tying back to the thread: assigning total = ... inside the loop will leave total as the last element’s quantity (what warned about); use += to accumulate. Initialize the accumulator to avoid "not definitely assigned" when the collection is empty. Watch for null references (the orders list or individual elements) and for overflow if totals can be very large (use long then). If the real intent was to return the last quantity rather than a sum, return an OptionalInt or handle the empty-list case explicitly so callers get a clear result. ’s follow-up indicates the compile issue was resolved once the signature and initialization were fixed.

Recommended Answers

All 4 Replies

Please post the full text of the error message that shows where the error occurs.
What statement causes the exception?

method whose result type is void?

The posted method is defined with return type of void on line 1. It can not return a value on line 12.
Change its return type to be the same type as total if you want to return a value.

BTW total won't be an accumulation of values, it will hold the last value received in line 7

The error occurs on the return total; The getQuantity() method is being called from another class.

We cross posted. See my last post.

Thank you, I can't believe I didn't see that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.