如何获得一个整数数组列表的总和?
基本上我试着做一个程序,让老师输入牌号为每个学生一个测试,然后他们已经输入它给老师,他们输入
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);
}
我试图找出如何获取数组列表的总和的等级的
下面是你如何使用总结集合的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());
}
}
在您的code,你会做这样的等级
列表。您可以的你的循环后,将其设置为 gradetotal
的。
In your code, you would do this to the grade
list. You can set this to gradetotal
after your loop.
价值 - &GT;值
是说拿每个参数并返回。 流()
返回流
不具有和()
。 mapToInt
返回 IntStream
其中确实有无和()
。这价值 - &GT;值
告诉code如何每个元素转换在流
到整数
。因为每个元素是的已的一个整数
,我们仅仅需要返回每个元素。
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.