Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printf for sum and average

Tags:

java

printf

This is what I have:

  double[] miles = new double [10];

  double milesPerWeek = 26.0 / 10;
  double totalMiles = 0;
  double sum = 0;
  double average = 0;

  System.out.println("Week\tMiles");

  for (int i = 0; i < miles.length; i++){

     miles[i] += milesPerWeek;
     totalMiles += miles[i];

     System.out.printf("Week %d\t%.1f%n", i + 1, totalMiles);
  }
  for (int i = 0; i < miles.length; i++)
  {              
     sum = sum + miles[i];
     average = sum / miles.length;
  }
  System.out.printf("The total of miles run is: %.1f%n" + sum + "\n");

  System.out.printf("The average of miles run is: %.1f%n" + average);

This is the problem I'm having with sum and average. I cannot seem to format the decimal places using print f without this error message: The total of miles run is: Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.1f'

Can you please direct me as I need one decimal place.

like image 789
Janine McDaniel Avatar asked Mar 05 '26 02:03

Janine McDaniel


1 Answers

You need to pass the values as arguments, not concat them:

System.out.printf("The total of miles run is: %.1f%n\n", sum);

System.out.printf("The average of miles run is: %.1f%n", average);
like image 164
shmosel Avatar answered Mar 07 '26 14:03

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!