Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - How to get the sum of an Integer arraylist?

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...