John Duil
John Duil

Reputation: 11

How to divide arrays into groups?

How would I go about dividing arrays into quarters? For example, I want to ask the user to enter say 12 values. Then, divide them into 4 quarters and add the values in each quarter. I figured how to add all of them up, but I'm stuck on how to add them separately in groups. Thank You.

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
    }`

Upvotes: 1

Views: 336

Answers (3)

shmosel
shmosel

Reputation: 50716

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

Upvotes: 2

Kevin Anderson
Kevin Anderson

Reputation: 4592

You don't say specifically, but let's just assume that quarter #1 is entries 0 - 2 in 'salesData`; quarter #2 is entries 3 to 5, etc.

Here's one way to find and print the quarter totals:

    int salesData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    int qtotal[] = new int[4];
    for (int q = 0; q < 4; ++q) {
        qtotal[q] = 0;
        for (int i = 0; i < 3; ++i) {
            qtotal[q] += salesData[q * 3 + i];
        }
    }
    for (int q = 0; q < 4; ++q) {
        System.out.printf("Quarter #%d total: %d\n ", q + 1, qtotal[q]);
    }

Upvotes: 0

Eric
Eric

Reputation: 601

You are on the right track, you already know all the pieces you need.

  1. You know how to declare an array of a fixed size (12).
  2. You know how to write a for loop.
  3. You know how to index an array using the for loop counter.

So if I wanted to do the first quarter...

int firstQuarter = 0;
for (int i = 0; i < 3; i++)
{
  firstQuarter = firstQuarter + salesData[i];
}
System.out.println("1st Quarter" + firstQuarter);

You could easily write one of these blocks for each quarter, but I challenge you to find a more elegant solution. Good luck!

Upvotes: 0

Related Questions