如何获得整数数组列表的总和?
基本上我试图制作一个程序,允许老师为每个学生输入考试成绩,然后在他们输入成绩后,它会给老师他们输入的所有成绩的总和
Basically Im trying to make a program that allows a teacher to input grades for a test for each student then after they've inputted the grades it gives the teacher a sum of all the grades they inputted
public static void grades(){
List<Integer> grade = new ArrayList<Integer>();
int gradetotal = IntStream.of(grades).sum;/* sum */
int gradelistnumber = 1;
int inputedgrade = 0;
while(inputedgrade != -1){
System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
inputedgrade = sc.nextInt();
grade.add(inputedgrade);
gradelistnumber++;
}
System.out.println("Class Average: " + gradetotal / 50 * 100);
}
我想弄清楚如何获得数组列表 grades 的总和.
I'm trying to figure out how to get the sum of the array list grades .
以下是使用 Java 8 对集合求和的方法:
Here's how you sum a Collection using java 8:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String args[]) throws Exception {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(5);
System.out.println(numbers.stream().mapToInt(value -> value).sum());
}
}
在您的代码中,您将对 grade
列表执行此操作.您可以将其设置为 gradetotal
after 循环.
In your code, you would do this to the grade
list. You can set this to gradetotal
after your loop.
值 ->value 是说获取每个参数并返回它".stream()
返回一个没有 sum()
的 Stream
.mapToInt
返回一个 IntStream
,它确实具有 sum()
.那个 值 ->value
告诉代码如何将 Stream
中的每个元素转换为 Integer
.因为每个元素已经是一个Integer
,所以我们只需要返回每个元素.
value -> value
is saying "take each argument and return it". stream()
returns a Stream
which doesn't have sum()
. mapToInt
returns an IntStream
which does have sum()
. That value -> value
tells the code how to convert each element in the Stream
into an Integer
. Because each element is already an Integer
, we merely have to return each element.