0

This is my array c: [-33,-22,-11,-5,-4,-3,-2,-1,6,7,8,9,10,11,44,55,66,77,88]

I was able to find the sum by doing this and it worked:

System.out.println(Arrays.stream(c).sum()));

I tried a similar approach to get the average:

System.out.printf("%.2f",(Arrays.stream(c).sum()/c.length));

I got an IllegalFormatConversionException for that though. When I manually do the average on a calculator, it should come out to 15.78947...but I only want to round 2 places after the decimal. I have tried other statements but those kept giving be 15 as the average and cutting the decimals off. I need to compute the average within the print statement. How can I do this?

I want my output to look like this: 15.79

xson
  • 71
  • 1
  • 9
  • 2
    int / int is an int, you need a cast –  Apr 11 '15 at 20:53
  • BTW, the message is: "Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer", and it tells what the problem is. Not reading, nor posting the message, is your biggest mistake. – JB Nizet Apr 11 '15 at 20:55

2 Answers2

1
double average = Arrays.stream(numbers).average().getAsDouble();

This should do the trick.

Neumann
  • 551
  • 2
  • 6
  • 17
0

Arrays.stream(c).sum()/c.length is integer since both arguments are integer.

So you are trying to format Integer as float.

You need explicitly cast one of arguments to float (or double) to get decimal result.

Something like

Arrays.stream(c).sum()/(double)c.length
EvilOrange
  • 876
  • 1
  • 9
  • 17