简体   繁体   中英

Sum and Average of Java Array List Elements

I have an exception in my Java program. When I run this code:

ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
    total += sum.get(i);
    avg = total / sum.size();
    System.out.println("The Average IS:" + avg);
}

It prints each ArrayList index element then prints the average, but when I run this code:

for(int i = 0; i<sum.size(); i++)
    total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);

It prints the average, but I have not given the bracket of the for loop.

How does the code compare?

Lambda stream method in Java 8 can solve this in a easy way:

int myArray[] = { 1, 2, 3 };
Arrays.stream(myArray).average();

The brackets are use to define block of statement

By default, a loop or a condition only read one statement. A statement could be one line or a block of statement

So here is a line

total=total+sum.get(i);

and here is the block of statement

{
    total += sum.get(i);
    avg = total / sum.size();
    System.out.println("The Average IS:" + avg);
}

NOTE : You speak about exception but also said that there is an output in both cases, so I guess your exception is not a Java Exception but just some misunderstanding in this behavior.

EDIT : You should change avg type to accept decimal values and you are going to change a bit the line, the easier is to add a static value of float to convert the value :

float avg = 1.0f * total / sum.size();

Because there is a float here (1.0f), the result will be a float, if you only use integers, the result will be rounded in integer (even if you store it in a float).

From your question, I guess that you are learning Java.

If you are in Java 8, you might use Stream (see link for a better explanation):

  • The new Stream API allows to transform (map), filter values, etc.
  • It allows to collect them (see Collectors ), regrouping them by key (groupingBy), and in your case to compute a summary statistics.

The example below shows you how to do that using either an IntStream (a Stream tailored for int ) or a standard Stream :

IntSummaryStatistics stats = Arrays.asList(10, 15, 20)
  .stream()
  .mapToInt(Integer::intValue)
  .summaryStatistics()
;
// alternative
// IntSummaryStatistics stats2 = Arrays.asList(10, 15, 20)
//  .stream()
//  .collect(Collectors.summarizingInt(Integer::intValue))
// ;
System.out.println("average: " + stats.getAverage());
System.out.println("count: " + stats.getCount());
System.out.println("sum: " + stats.getSum());

See the javadoc for Collectors.summarizingInt .

In java curly braces are used to group the line of code. In first block of code

ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
    total += sum.get(i);
    avg = total / sum.size();
    System.out.println("The Average IS:" + avg);
}

in this code you are adding element to total and same time you are calculating average. Let us see each iteration

iteration 1: 
total = 10
avg = 10/3 = 3

iteration 2:
total = 25
avg = 25/3 = 8 

iteration 3: 
total = 45
avg = 45/3 = 15

But in case of second code block

for(int i = 0; i<sum.size(); i++)
    total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);

here code is equivalent to

for(int i = 0; i<sum.size(); i++){
    total = total+sum.get(i);
}
avg = total / sum.size();
System.out.println("The Average IS:" + avg);

so in for loop, it calculates total only as

iteration 1: total = 10
iteration 2: total = 15
iteration 2: total = 45

after completion of block value of total is 45

and after block, actual average is calculated as:

avg = 45/3 = 15

In java if we don't provide curly braces to group block of code inside for, if and while by default considered only single line inside the block and execute it repeatedly based on condition.

Exception is according to you Is not achieving the expected behaviour for an average on the elements of the collections. So, as the earlier answer it boiles down to the Java syntax for working with the Loops/conditions/statements that how we use the { // code } By defaults a single line of code statement followed after Loops/conditions does not need to wrap in the braces {}

Here the first snippet uses a block of statement to derive average on each element by collecting it in total and dividing with size of collection. Whereas, the second snippet does the collection of total for all element at first and then go for finding average.

You need to account for the data precisions when deriving mathematical values like avg and use the appropriate primitive data type.

If you remove the braces, the for loop header refers to the (one) very next statement, so the following two examples are equal:

for(int i=0; i<sum.size(); i++)
    total=total+sum.get(i);
    avg=total/sum.size();
    System.out.println("The Average IS:" + avg);

for(int i=0; i<sum.size(); i++) {
    total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);

When you leave the brackets for the loop away, then just the first following line will be part of the loop. That means:

for(int i=0; i<sum.size(); i++)
         total=total+sum.get(i);
         avg=total/sum.size();
         System.out.println("The Average IS:" + avg);

Is equivalent to

for(int i=0; i<sum.size(); i++){
     total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);

Same counts also for eg if/else.

1st

for(int i = 0; i < sum.size(); i++)
    {
        total += sum.get(i);
    }

2nd

for(int i = 0; i < sum.size(); i++)
        total += sum.get(i); 
//but in this for loop it considers only one statement as inside for loop

3rd

for(int i = 0; i < sum.size(); i++)
        total += sum.get(i);//only this statement is considered as inside the loop 
    System.out.println("hello");//this statements is not considered inside the loop

1st and 2nd for loops are same

You need to insert bracket in 2nd code of for loop the following.

    for(int i = 0; i<sum.size(); i++) {
        total = total+sum.get(i);
        avg = total / sum.size();
        System.out.println("The Average IS:" + avg);
   }

Because if you don't insert bracket in for loop, only one line under the for loop will execute for looping process. So you need to make bracket for starting line to ending line that you want to execute in looping process.

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