Even if you declared average
to be double
, the sum
and counter
variables are int
, so Java still uses integer division before assigning it to average
, e.g. 5 / 10
results in 0
instead of 0.5
.
Cast one of the variables to double
before the division to force a floating point operation:
double average;
...
average = (double) sum / counter;
You can include the first number in your calculation by processing it before you go into the while loop (if it's not the sentinel value).