Java 数组列表元素的总和和平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41501002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:26:27  来源:igfitidea点击:

Sum and Average of Java Array List Elements

java

提问by Arm Avi

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

我的 Java 程序中有一个例外。当我运行此代码时:

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 ArrayListindex element then prints the average, but when I run this code:

它打印每个ArrayList索引元素,然后打印平均值,但是当我运行此代码时:

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

它打印平均值,但我没有给出for循环的括号。

How does the code compare?

代码对比如何?

回答by C. L.

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

如果去掉大括号,for 循环头会引用(一个)紧接着的语句,所以下面两个例子是等价的:

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

回答by GAlexMES

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 e.g. if/else.

例如,if/else 也同样重要。

回答by AxelH

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 exceptionis not a Java Exception but just some misunderstanding in this behavior.

注意:您谈到异常,但也说在这两种情况下都有输出,所以我猜您的异常不是 Java 异常,而只是对这种行为的一些误解。

EDIT : You should change avgtype 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 :

编辑:您应该更改avg类型以接受十进制值,并且您将更改一点行,更容易的是添加浮点数的静态值来转换值:

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

因为这里有一个浮点数(1.0f),所以结果会是一个浮点数,如果只使用整数,结果会以整数四舍五入(即使你存储在一个浮点数中)。

回答by prashanth

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

第一个和第二个 for 循环相同

回答by THA

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

您需要在以下 for 循环的第二个代码中插入括号。

    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.

因为如果不在for循环中插入括号,for循环下只有一行会执行for循环过程。因此,您需要为要在循环过程中执行的起始行到结束行制作括号。

回答by NoDataFound

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

从你的问题来看,我猜你正在学习Java。

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

如果您使用的是 Java 8,则可以使用Stream(请参阅链接以获得更好的解释):

  • The new StreamAPI 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.
  • 新的StreamAPI 允许转换(映射)、过滤值等。
  • 它允许收集它们(请参阅Collectors),通过键(groupingBy)将它们重新分组,并在您的情况下计算汇总统计信息。

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

下面的示例向您展示了如何使用IntStream(为Stream量身定制的int)或标准来做到这一点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.

请参阅Collectors.summarizingInt的 javadoc 。

回答by Devram Kandhare

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

在 java 中,花括号用于对代码行进行分组。在第一个代码块中

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

所以在 for 循环中,它只计算总数为

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

after completion of block value of total is 45

完成区块后的总价值为 45

and after block, actual average is calculated as:

并在block之后,实际平均值计算如下:

avg = 45/3 = 15

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

在 java 中,如果我们不提供花括号来将代码块分组到for、if 和 while默认情况下只考虑块内的一行并根据条件重复执行它。

回答by Rizwan

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 {}

例外是根据您的说法 未达到集合元素平均值的预期行为。因此,作为较早的答案,它归结为用于处理循环/条件/语句的 Java 语法,我们如何使用{ // code }默认情况下,在循环/条件之后的单行代码语句不需要用大括号括起来 {}

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.

在推导 avg 等数学值并使用适当的原始数据类型时,您需要考虑数据精度。

回答by Cai Yongji

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

Java 8 中的 Lambda 流方法可以很简单地解决这个问题:

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