我如何将阵列划分为四分之一? 例如,我想要求用户输入12个值。然后,将它们分成4个季度,并在每个季度添加值。我想到了如何添加所有这些,但我仍然坚持如何在组中单独添加它们。 谢谢。
import java.util.Scanner;
import java.util.stream.*;
public class SalesData {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] salesData = new int[12];
int monthNumber=1;
for (int i = 0; i < 12; i++) {
System.out.println("Please enter the data for month "+monthNumber);
salesData[i] = keyboard.nextInt();
int newNumber=monthNumber++;
}
System.out.println("The first quarter total is ");
System.out.println("The second quarter total is ");
System.out.println("The third quarter total is ");
System.out.println("The fourth quarter total is ");
double sum = IntStream.of(salesData).sum();
System.out.println("The Annual Sales Total is "+sum);
}//end main
}`
答案 0 :(得分:2)
String[] quarters = {"first", "second", "third", "fourth"};
for (int i = 0; i < 12; i += 3)
System.out.printf("The %s quarter total is %d%n",
quarters[i / 3],
Arrays.stream(salesData, i, i + 3).sum());
答案 1 :(得分:0)
你走在正确的轨道上,你已经知道了所需的所有部分。
所以,如果我想第一季度......
int firstQuarter = 0;
for (int i = 0; i < 3; i++)
{
firstQuarter = firstQuarter + salesData[i];
}
System.out.println("1st Quarter" + firstQuarter);
您可以轻松地为每个季度编写其中一个块,但我挑战您找到更优雅的解决方案。祝你好运!
答案 2 :(得分:0)
你没有具体说明,但我们假设第一季度#1是'salesData`中的条目0 - 2;第二季度是第3至第5项等。
以下是查找和打印季度总计的一种方法:
{{1}}