我是Java的新手,目前正在参加我的第一堂Java课。我试图添加一个需要用户输入的数组,而不仅仅是用预定的数字填充数组。获取数组总和的代码是否与预定数组相同?这是我的代码。

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;

10-08 16:12