Multidimensional Arrays

Paul Ngugi - May 29 - - Dev Community

A two-dimensional array consists of an array of one-dimensional arrays and a three-dimensional array consists of an array of two-dimensional arrays. Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n.

The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n-dimensional arrays for n >= 3. For example, you may use a three-dimensional array to store exam scores for a class of six students with five exams, and each exam has two parts (multiple-choice and essay). The following syntax declares a three-dimensional array variable scores, creates an array, and assigns its reference to scores.

double[][][] scores = new double[6][5][2];

You can also use the short-hand notation to create and initialize the array as follows:

double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};

scores[0][1][0] refers to the multiple-choice score for the first student’s second exam, which is 9.0. scores[0][1][1] refers to the essay score for the first student’s second exam, which is 22.5. This is depicted in the following figure:

Image description

A multidimensional array is actually an array in which each element is another array. A three-dimensional array consists of an array of two-dimensional arrays. A two-dimensional array consists of an array of one-dimensional arrays. For example, suppose x = new int[2][2][5], and x[0] and x[1] are two-dimensional arrays. X[0][0], x[0][1], x[1][0], and x[1][1] are one-dimensional arrays and each contains five elements. x.length is 2, x[0].length and x[1].length are 2, and X[0][0].length, x[0][1].length, x[1][0].length, and x[1][1].length are 5.

Case Study: Daily Temperature and Humidity

Suppose a meteorology station records the temperature and humidity every hour of every day and stores the data for the past ten days in a text file named Weather.txt. Each line of the file consists of four numbers that indicate the day, hour, temperature, and humidity. The contents of the file may look like the one in (a).

Image description

Note that the lines in the file are not necessarily in increasing order of day and hour. For example, the file may appear as shown in (b).
Your task is to write a program that calculates the average daily temperature and humidity for the 10 days. You can use the input redirection to read the file and store the data in a three-dimensional array named data. The first index of data ranges from 0 to 9 and represents 10 days, the second index ranges from 0 to 23 and represents 24 hours, and the third index ranges from 0 to 1 and represents temperature and humidity, as depicted in the following figure:

Image description

Note that the days are numbered from 1 to 10 and the hours from 1 to 24 in the file. Because the array index starts from 0, data[0][0][0] stores the temperature in day 1 at hour 1 and data[9][23][1] stores the humidity in day 10 at hour 24. The program is given below:

Image description

Day 0's average temperature is 77.7708
Day 0's average humidity is 0.929583
Day 1's average temperature is 77.3125
Day 1's average humidity is 0.929583
. . .
Day 9's average temperature is 79.3542
Day 9's average humidity is 0.9125

You can use the following command to run the program:

java Weather < Weather.txt

A three-dimensional array for storing temperature and humidity is created in line 9. The loop in lines 13–20 reads the input to the array. You can enter the input from the keyboard, but doing so will be awkward. For convenience, we store the data in a file and use input redirection to read the data from the file. The loop in lines 25–28 adds all temperatures for each hour in a day to dailyTemperatureTotal and all humidity for each hour to dailyHumidityTotal. The average daily temperature and humidity are displayed in lines 31–32.

Case Study: Guessing Birthdays

package demo;
import java.util.Scanner;

public class GuessBirthdayUsingArray {

    public static void main(String[] args) {
        int day = 0; // Day to be determined
        int answer;

        int[][][] dates = {
                {
                    { 1,  3,  5,  7},
                    { 9, 11, 13, 15},
                    {17, 19, 21, 23},
                    {25, 27, 29, 31}
                },
                {
                    {  2, 3,  6,  7},
                    {10, 11, 14, 15},
                    {18, 19, 22, 23},
                    {26, 27, 30, 31}
                },
                {
                    {  4, 5,  6,  7},
                    {12, 13, 14, 15},
                    {20, 21, 22, 23},
                    {28, 29, 30, 31}
                },
                {
                    { 8,  9, 10, 11},
                    {12, 13, 14, 15},
                    {24, 25, 26, 27},
                    {28, 29, 30, 31}
                },
                {
                    {16, 17, 18, 19},
                    {20, 21, 22, 23},
                    {24, 25, 26, 27},
                    {28, 29, 30, 31}
                },
        };

        // Create a Scanner
        Scanner input = new Scanner(System.in);

        for(int i = 0; i < 5; i++) {
            System.out.println("Is your birsthday in Set" + (i + 1) + "?");
            for(int j = 0; j < 4; j++) {
                for(int k = 0; k < 4; k++)
                    System.out.printf("%4d", dates[i][j][k]);
                System.out.println();
            }

            System.out.print("\nEnter 0 for No and 1 for Yes: ");
            answer = input.nextInt();

            if(answer == 1)
                day += dates[i][0][0];
        }

        System.out.println("Your birthday is " + day);
    }

}

Enter fullscreen mode Exit fullscreen mode

A three-dimensional array dates is created in Lines 10–41. This array stores five sets of numbers. Each set is a 4-by-4 two-dimensional array.
The loop starting from line 46 displays the numbers in each set and prompts the user to answer whether the birthday is in the set (lines 54–55). If the day is in the set, the first number (dates[i][0][0]) in the set is added to variable day (line 58).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .