Chewy
Chewy

Reputation: 85

printing out the average of an array

I have a method below that is getting the average of an array. I need the output to go too two decimal places. In my client program I have the following printf statement which prints out the average. I know my average method works because I added a simple println(getAverage()) which returned the correct result without going too two decimal places.

Please note that I do have a a method that checks for duplicates, so the array would hold the following values {6, 3, 5, 2, 7, 9, 4}.

I believe the issue is with my printf statement. Please advise, thx.

** getAverage() Method **

public double getAverage() {
  int sum = 0;
  double average;

  for (int i = 0; i < nElems; i++) {
     sum += arr[i];   
  }
  average = (sum * 1.0) / nElems;
  return average;
}

** Client program **

 public static void main(String[] args) {
  // ** Use for initial debugging ** //

  ArrayDataPlus d1 = new ArrayDataPlus(10);   
  d1.display();
  insert(d1, 6);
  insert(d1, 3);
  insert(d1, 6);
  insert(d1, 5);
  insert(d1, 2);
  insert(d1, 7);
  insert(d1, 6);
  insert(d1, 9);
  insert(d1, 7);
  insert(d1, 2);
  insert(d1, 4);

  d1.display();

  System.out.printf("Avg = %1.2\n", d1.getAverage());

}

Upvotes: 0

Views: 478

Answers (1)

David Conrad
David Conrad

Reputation: 16359

%1.2 needs a format specifier such as f, as in %1.2f.

Upvotes: 2

Related Questions