How to get the sum of an Integer arraylist?

风格不统一 提交于 2019-12-13 08:57:09

问题


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

I'm trying to figure out how to get the sum of the array list grades .


回答1:


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

In your code, you would do this to the grade list. You can set this to gradetotal after your loop.

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.




回答2:


Instead of maintaining an array, why not just keep two temporary variables - a count and a summation?

int gradetotal = 0;
int gradelistnumber = 0;
int inputedgrade = 0;
while(inputedgrade != -1){
    System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
    inputedgrade = sc.nextInt();
    gradetotal = gradetotal + inputedgrade;
    gradelistnumber++;
}


来源:https://stackoverflow.com/questions/26242176/how-to-get-the-sum-of-an-integer-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!