gpt4 book ai didi

java - Java中获取数组的总和

转载 作者:行者123 更新时间:2023-12-02 04:54:14 24 4
gpt4 key购买 nike

我对 Java 非常陌生,目前正在学习我的第一个 Java 类(class)。我正在尝试添加一个接受用户输入的数组,而不仅仅是用预定的数字填充数组。获取数组总和的代码是否与预定数组相同?这是我的代码。

import java.util.Scanner;

public class Main {

public static void main(String[] args)
{

Scanner scan = new Scanner(System.in);

int[] monthSales = new int[12];

String[] monthNames = new String[12];
monthNames[0] = "January";
monthNames[1] = "February";
monthNames[2] = "March";
monthNames[3] = "April";
monthNames[4] = "May";
monthNames[5] = "June";
monthNames[6] = "July";
monthNames[7] = "August";
monthNames[8] = "September";
monthNames[9] = "October";
monthNames[10] = "November";
monthNames[11] = "December";

int i = 0;

while (i <= 11)
{
System.out.println("What was the sales for the month of " + monthNames[i] + ": ");
monthSales[i] = scan.nextInt();
i++;

}
}
}

最佳答案

对数组求和的两种方法:

1) 在 Java 8 中你可以这样做(假设数组名为“monthSales”):

int sum = IntStream.of(monthSales).sum();
System.out.println("The sum is " + sum);

2)或者你也可以这样做:

int sum = 0;

for (int i : monthSales)
sum += i;

关于java - Java中获取数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com