我是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++;
}
}
}
答案 0 :(得分:2)
对数组求和的两种方法:
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;
答案 1 :(得分:0)
是的,它只是喜欢:
int sum = 0;
for (int i=0; i<monthSales.length; i++)
sum += monthSales[i];
请注意:
使用for循环代替while,这将是非常易读,通用并使用i < monthNames.length
代替i <= 11
答案 2 :(得分:0)
只需遍历数组并将值添加到变量
int sum = 0;
for(int value: monthSales)
sum += value;