Calculate average in java

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.

ShareFollowedited May 24 ’17 at 13:20answered Aug 10 ’11 at 9:02Thomas83.4k1212 gold badges115115 silver badges149149 bronze badges

  • If i was to use args.lengths instead of nums.length what would i do to “sum += nums[i];” ? – syncoroll Aug 10 ’11 at 9:50
  • @syncoroll Rereading your updated question I also updated my answer. – Thomas Aug 10 ’11 at 10:02
  • integer overflow is not taken care of – banjara Jul 27 ’12 at 9:16
  • 1You should check if 0 == args.length, if you don’t do this then you you get “division by zero” on line double average = sum/args.length; when args.length is 0. – Developer Marius Žilėnas Jan 7 ’14 at 7:18
  • 2@MariusŽilėnas you’re right and there are probably still a couple of further errors that might occur, but for simplicity’s sake and in the case of the OP those are omitted and left for the implementor to handle. – Thomas Jan 7 ’14 at 13:51

Show 3 more comments4

int values[] = { 23, 1, 5, 78, 22, 4};

int sum = 0;
for (int i = 0; i < values.length; i++)
    sum += values[i];

double average = ((double) sum) / values.length;

Leave a Comment