Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate average in java

EDIT: I've written code for the average but I don't know how to make it so that it also uses ints from my args.length rather than the array.

I need to write a java program that can calculate:

  1. the number of integers read in
  2. the average value – which need not be an integer!

NOTE: I don't want to calculate the average from the array but the integers in the args.

Currently I have written this:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
    System.out.println(count);
}
    
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
    result += nums[i];
}
System.out.println(result/count)

Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?

Thanks in advance.

like image 233
syncoroll Avatar asked Dec 07 '22 19:12

syncoroll


1 Answers

Just some minor modification to your code will do (with some var renaming for clarity) :

double sum = 0; //average will have decimal point

for(int i=0; i < args.length; i++){
   //parse string to double, note that this might fail if you encounter a non-numeric string
   //Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
   sum += Double.valueOf( args[i] ); 
}

double average = sum/args.length;

System.out.println(average );

Note that the loop can also be simplified:

for(String arg : args){
   sum += Double.valueOf( arg );
}

Edit: the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.

Update:

As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:

BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
  sum = sum.add( new BigDecimal( arg ) );
}

This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):

  • Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
  • The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.
like image 136
Thomas Avatar answered Dec 10 '22 13:12

Thomas