简体   繁体   中英

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 int s 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.

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 .
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;

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?

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 .

I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.

public double average(ArrayList<Double> x) {
    double sum = 0;
    for (double aX : x) sum += aX;
    return (sum / x.size());
}

If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html

You'll fall into true luv!

public class MainTwo{
    public static void main(String[] arguments) {
        double[] Average = new double[5];
        Average[0] = 4;
        Average[1] = 5;
        Average[2] = 2;
        Average[3] = 4;
        Average[4] = 5;
        double sum = 0;
        if (Average.length > 0) {
            for (int x = 0; x < Average.length; x++) {
                sum+=Average[x];
                System.out.println(Average[x]);
            }
            System.out.println("Sum is " + sum);
            System.out.println("Average is " + sum/Average.length);
      }
   }
}
 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length

for 1. the number of integers read in, you can just use length property of array like:

int count = args.length

which gives you no of elements in an array. And 2. to calculate average value: you are doing in correct way.

Instead of:

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

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

If you're trying to get the integers from the command line args, you'll need something like this:

public static void main(String[] args) {
    int[] nums = new int[args.length];
    for(int i = 0; i < args.length; i++) {
        try {
            nums[i] = Integer.parseInt(args[i]);
        }
        catch(NumberFormatException nfe) {
            System.err.println("Invalid argument");
        }
    }

    // averaging code here
}

As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).

Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM