如何获得整数数组列表的总和?

编程入门 行业动态 更新时间:2024-10-27 10:29:34
本文介绍了如何获得整数数组列表的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

基本上我试图制作一个程序,允许老师为每个学生输入考试成绩,然后在他们输入成绩后,它会给老师他们输入的所有成绩的总和

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

我想弄清楚如何获得数组列表 grades 的总和.

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

推荐答案

以下是使用 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());
    }
}

在您的代码中,您将对 grade 列表执行此操作.您可以将其设置为 gradetotal after 循环.

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

<代码>值 ->value 是说获取每个参数并返回它".stream() 返回一个没有 sum()Stream.mapToInt 返回一个 IntStream,它确实具有 sum().那个 值 ->value 告诉代码如何将 Stream 中的每个元素转换为 Integer.因为每个元素已经是一个Integer,所以我们只需要返回每个元素.

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 07:16:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   总和   如何获得   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!