简体   繁体   中英

How to calculate the average in this case? (JAVA )

I have a set of numbers that I named age[]. I want to calculate the average of all the elements contained in age[] without calculating the sum separately. Not like this:

int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

That is actually too long to write. Imagine if a have 100 of elements, it'll be too hard.

int age[] = { 20, 17, 19, 22, 18, 18 };
String[] names = { "Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan" };
for (int i = 0; i <= 5; i++) {
    if (age[i] >= 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. And he's from Mars!");
    }
    if (age[i] < 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. He is from Wakanda!");
    }
}

int j = 0;
int avg = (age[j] + age[j++]) / age.length;

System.out.println("Their average age is :" + avg + " years.");

int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

System.out.println("Their correct average age is :" + avg2 + " years.");

That's what I've done but I didn't find the shortcut. Please help me to solve this if possible. Thanks.

You could sum the age values while you iterate the array(s). Don't hardcode the length in the for loop. Use an else instead of two if (s). Something like,

int age[]= { 20, 17, 19, 22, 18, 18};
String[] names = {"Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan"};
int total = 0;
for (int i = 0; i < age.length; i++) {
    total += age[i];
    if (age[i] >= 20) {
        System.out.println(names[i] +" is "+ age[i] +" years old. And he's from Mars!");
    } else {
        System.out.println(names[i] +" is "+ age[i] +" years old. He is from Wakanda!");
    }
}
double avg = total / (double) age.length;
System.out.println("Their average age is :" + avg + " years.");

One of the simplest ways is to use Java Streams API .

double avg = Arrays.stream(age).average().getAsDouble();

Demo :

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int age[] = { 20, 17, 19, 22, 18, 18 };
        double avg = Arrays.stream(age).average().getAsDouble();
        System.out.println(avg);
    }
}

Output :

19.0

Here is a somewhat different way of doing it.

  • Use IntStream to streams the array indices.
  • employ map to print the ages for each individuals
  • then calculate the average and
    • if an average is present, print it
    • else print an informatory message
int ages[] = 
    {20,17,19,22,18,18};
String[] names =
    {"Ahmed","Sam","Mandi","Amine","John","Rayan"};

IntStream.range(0, ages.length).map(i -> {
    int age = ages[i];
    if (age >= 20) {
        System.out.println(names[i] + " is " + age
                + " years old. And he's from Mars!");
    } else {
        System.out.println(names[i] + " is " + age
                + " years old. He is from Wakanda!");
    }
    return age;
}).average().ifPresentOrElse(
        avg -> System.out
                .println("\nTheir average age is: " + avg + " years."),
        () -> System.out.println("No ages were supplied"));

prints

Ahmed is 20 years old. And he's from Mars!
Sam is 17 years old. He is from Wakanda!
Mandi is 19 years old. He is from Wakanda!
Amine is 22 years old. And he's from Mars!
John is 18 years old. He is from Wakanda!
Rayan is 18 years old. He is from Wakanda!

Their average age is: 19.0 years.

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