Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...