0

I am supposed to find the average of a bunch of given numbers after adding all of them up then dividing by the number of numbers given to me and the average must have 3 decimal numbers so for instead of 45.0 it would be 45.000 and mine works but only if the last number is not 0.

import java.util.Scanner;
import static java.lang.System.*;

public class Average
{
   private String line;
   private double average, sum, count;

   public Average()
   {
     setLine("");
   }

   public Average(String s)
   {
     setLine(s);
   }

 public void setLine(String s)
 {
   line = s;
   sum = 0.0;
   count = 0.0;
   average = 0.0;
 }

 public double getCount()
 {
  int num = 0;
  while(num<line.length())
  {
    if(line.charAt(num) == 32)
    {
      count ++;
      num ++;
    }
    else
      num ++;
  }
  count ++;
  return count;
 }

 public double getSum()
 {
  Scanner bobby = new Scanner(line);
  while(bobby.hasNextInt())
    sum = sum + bobby.nextInt();
  return sum;
 }

 public double getAverage()
 {
  average = getSum()/getCount();
  average = average*1000;
  if(average%10>4)
  {
  average = Math.floor(average);
  average ++;
  average = average/1000.0;
  }
  else
  {
  average = Math.floor(average);
  average = average/1000.0;
  }
  return average;
  }

 public String getLine()
 {
  return line;
 }

 public String toString()
 {
  return "";
 }
}

This is my runner file

import java.util.Scanner;
import static java.lang.System.*;

public class AverageRunner
{
   public static void main( String args[] )
   {
     String s = "9 10 5 20";
     Average bob = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob.getAverage());
     System.out.println();

     s = "11 22 33 44 55 66 77";
     Average bob1 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob1.getAverage());
     System.out.println();

     s = "48 52 29 100 50 29";
     Average bob2 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob2.getAverage());
     System.out.println();

     s = "0";
     Average bob3 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob3.getAverage());
     System.out.println();

     s = "100 90 95 98 100 97";
     Average bob4 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob4.getAverage());
 }
}
Anon Dog
  • 25
  • 5

1 Answers1

1

Use DecimalFormat:

DecimalFormat df = new DecimalFormat("#.000"); 
System.out.println("Nummber: " + df.format(1.2345));
devgianlu
  • 1,547
  • 13
  • 25