Calculate average in java

143,711

Solution 1

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.

Solution 2

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;

Solution 3

This

for (int i = 0; i<args.length -1; ++i)
    count++;

basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?

Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?

Solution 4

It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.

  • In your case, you want to convert args which is String[] into double or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
  • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
  • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
Share:
143,711
syncoroll
Author by

syncoroll

Learning java for the first time.

Updated on July 09, 2022

Comments

  • syncoroll
    syncoroll almost 2 years

    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.

  • syncoroll
    syncoroll almost 13 years
    I got an error for using args. "Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from element type String to int"
  • syncoroll
    syncoroll almost 13 years
    If i was to use args.lengths instead of nums.length what would i do to "sum += nums[i];" ?
  • Thomas
    Thomas almost 13 years
    Note that res /= count will do integer division and thus would most certainly yield the wrong result (the OP states that the average may contain decimal points).
  • Thomas
    Thomas almost 13 years
    @syncoroll You didn't tell us what args actually is - thus it might be assumed it is int[] args. Most likely you have String[] args (it's a main method, right?) - thus you'd have to change the for loop to for( String a : args) and call res += Integer.parseInt( a) inside.
  • Thomas
    Thomas almost 13 years
    @syncoroll Rereading your updated question I also updated my answer.
  • GrandMarquis
    GrandMarquis almost 13 years
    You know, i won't test code for your homework! This is just a way of doing it, an algorithm.. it should work, it depends on the type of your vars..
  • banjara
    banjara almost 12 years
    integer overflow is not taken care of
  • Thomas
    Thomas almost 12 years
    @zuxqoj That's true but I doubt this will be a problem here and I'd rather like to keep the example simple. I'll add another example though.
  • Developer Marius Žilėnas
    Developer Marius Žilėnas over 10 years
    You 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.
  • Thomas
    Thomas over 10 years
    @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.
  • huseyin
    huseyin about 7 years
    sum += Double.valueOf( args ); should be sum += Double.valueOf( arg );
  • Thomas
    Thomas about 7 years
    @Andromeda you're right, I fixed it in both snippets.