如何获得一个整数数组列表的总和? [英] How to get the sum of an Integer arraylist?

查看:80
本文介绍了如何获得一个整数数组列表的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我试着做一个程序,让老师输入牌号为每个学生一个测试,然后他们已经输入它给老师,他们输入

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.

这篇关于如何获得一个整数数组列表的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆