CommonDocs.org

This chapter expands on the knowledge discussed about arrays in Chapter 9. You will learn about multidimensional arrays, starting with two-dimensional arrays.

The arrays and ArrayLists in the previous two chapters were all one-dimensional arrays. You can think of them like a linear structure of data, where each element in the array comes directly after the element before it.

Multidimensional arrays are arrays that occupy over one dimension. The simplest multidimensional array is a two-dimensional (2D) array. You could think of this like a table, with rows and columns, instead of just one single line.

1D/2D Array VisualizationImage: Kevin Olson · CC BY-NC-SA

2D Arrays

A two-dimensional array is a data structure with two dimensions. You can think of it as a table with rows and columns. Keep in mind that data structures are abstract computer concepts. Your computer does not implicitly know what part of the index represents a "row" or the "column." How you structure your array is entirely up to you.

2D arrays are created much like 1D arrays. The difference is the amount of indices defined.

1//creating a 1D array
2int[] myArray = new int[6];
3
4//creating a 2D array 6x4 (total 24 values)
5int[][] myBiggerArray = new int[6][4];

In the example below, a 3x2 array is created. The first index can be thought of as the row in the table, where each row is a different student. The second index is the column - the first column being the student's ID number and the second column being their grade. There are 3 rows of students in this array, and 2 columns, so it's a 3x2 array with a total of six int values.

1public static void main(String[] args) {
2
3    //a new three by two array
4    int[][] studentGrades = new int[3][2];
5
6    //the first index for each student, the second for the different values associated with them (id and grade)
7    studentGrades[0][0] = 432;
8    studentGrades[0][1] = 92;
9    studentGrades[1][0] = 433;
10    studentGrades[1][1] = 75;
11    studentGrades[2][0] = 435;
12    studentGrades[2][1] = 88;
13
14    //print out the student ids and their grades
15    for(int i = 0; i < 3; i++){
16        System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "%");
17    }
18
19}
Terminal
The student with ID number: 432 has a grade of 92%
The student with ID number: 433 has a grade of 75%
The student with ID number: 435 has a grade of 88%

Extra Grades

Now, let's examine a situation in which we want to add multiple grades to the array, rather than just one. The first column will remain the student's id, the second their English grade, followed by their Math and Science grades.

There is no need to create a three-dimensional array. We are just adding more columns to the existing 2D array.

The same three students will be kept from the previous example. So we need to create a 3x4 array,

1//a new three by four
2int[][] studentGrades = new int[3][4];
3
4//the first index can hold the student's id number, the second, their grade.
5studentGrades[0][0] = 432;
6studentGrades[0][1] = 92;
7studentGrades[0][2] = 87;
8studentGrades[0][3] = 97;
9studentGrades[1][0] = 433;
10studentGrades[1][1] = 75;
11studentGrades[1][2] = 80;
12studentGrades[1][3] = 96;
13studentGrades[2][0] = 435;
14studentGrades[2][1] = 88;
15studentGrades[2][2] = 92;
16studentGrades[2][3] = 69;
17
18//print out the student ids and their grades
19for(int i = 0; i < 3; i++){
20    System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "% in English, " + studentGrades[i][2] + "% in Math, " + studentGrades[i][3] + "% in Science.");
21}
Terminal
The student with ID number: 432 has a grade of 92% in English, 87% in Math, 97% in Science.
The student with ID number: 433 has a grade of 75% in English, 80% in Math, 96% in Science.
The student with ID number: 435 has a grade of 88% in English, 92% in Math, 69% in Science.

.length

Using .length returns the static value holding the length of an array. In the above example, it will return 3, as that is the length of the first dimension of the array. To get the length of the second dimension, you need to add a blank [0] to the reference variable. In the 3x4 array, studentGrades.length returns 3, and studentGrades[0].length returns 4.

Sample Problem

Directions: Using the 3x4 array from the above extra grades section (you may just copy/paste it into a project), create an algorithm that finds each student's average grade across all three subjects, and prints it to the screen. Do this using an outer loop which iterates through the students, and an inner loop that iterates through the grades.

Sample Output:

1Student with id: 432 has an average grade of: 92.0%
2Student with id: 433 has an average grade of: 83.66666666666667%
3Student with id: 435 has an average grade of: 83.0%

Shorthand Syntax

Recall that a 1D array can be declared, initialized, and populated with values using this shorthand syntax:

1int[] myArray = {5, 10, 15, 20, 25};

The same can be done with 2D arrays. In this example, a 2x3 array is created using shorthand syntax.

1int[][] anotherArray = {{5,10,15},{10,20,30}};

The outer part of the array {A,B} is the first dimension of the array. The inner part {{x,y,z},{x,y,z}} is the second dimension.

1//this array is functionally equivalent
2int[][] anotherArray = {{5,10,15},{10,20,30}};
3
4//to this array
5int[][] anArray = new int[2][3];
6anArray[0][0] = 5;
7anArray[0][1] = 10;
8anArray[0][2] = 15;
9anArray[1][0] = 10;
10anArray[1][1] = 20;
11anArray[1][2] = 30;

Another way to format the 2D array with shorthand is to separate the first dimension of elements by line, and the second element into rows. This way may be more visually pleasing and easy to understand.

1int[][] anotherArray = {
2	  {5,10,15},
3	  {10,20,30}
4};

Table Printer Assignment

Instructions: Look at the table of Strings below. Take the information in the table cells, place them in an array, and print the table to the screen in a nicely formatted manner. Use vertical bars | to create the edges of the cells.

Define the array in the main method, then print the array using a separate method. A basic template is provided below.

To keep each column the same width, you may add spaces to the end of the strings, so each string in the column has the same width of characters.

NameFav ColorFav FoodFav Place
JackVioletTacosBeach
SammyBlackSushiNew York
JoeyGreenSteakJapan

Sample Output:

Terminal
|Name |Fav Color|Fav Food|Fav Place|
|Jack |Violet   |Tacos   |Beach    |
|Sammy|Black    |Sushi   |New York |
|Joey |Green    |Steak   |Japan    |

Starting Code

Here is some code to help you get started.

1public class Main {
2    public static void main(String[] args) {
3
4        //Create the Array
5        String studentData[][] = {
6                //data here
7        };
8
9        tablePrinter(studentData);
10
11    }
12
13    /**
14     * @param arr The array being printed to the screen in a nicely formatted manner
15     */
16    public static void tablePrinter(String[][] arr) {
17
18
19    }
20
21}

3D Arrays

Adding a third dimension to an array works the same way as a 2D array. Visually, you can think of a 3D array like a cube.

In the illustration, the first index is the plane or depth of the array, the second is the row, and the third is the column.

Creating a 3D array is the same as a 1D or 2D array, with the extra brackets for the extra indices.

1//a 3x4x4 array
2int[][][] array = new int [3][4][4];

Yearly Gradebook Example

Below is a 3D array created with shorthand syntax. It contains the grades of 3 senior students, in four different subjects, across the past 4 years. So the three dimensions are year, student, and subject.

1int grades[][][] = {
2        //year zero
3        {   //student 0   student 1       student 2
4            {89,95,85,93},{99,82,95,90},{91,87,90,77}
5        },
6        //year one
7        {   //student 0   student 1       student 2
8            {90,90,88,90},{92,87,86,89},{95,95,90,87}
9        },
10        //year two
11        {   //student 0   student 1       student 2
12            {90,80,90,75},{85,81,79,81},{99,98,90,89}
13        },
14        //year three
15        {   //student 0   student 1       student 2
16            {92,82,81,78},{89,81,74,85},{97,85,89,90}
17        }
18};

The way it's setup, the first index is the year from 0 to 3, where 0 is the current year and 3 is 3 years ago. The second index is the student, numbered 0 through 2, for a total of 3 students. The third index is the subject, 0 for Math, 1 for English, 2 Science, and 3 History. The array may be used to access the grades of any of the three students in any of the four subjects across the past four years.

1System.out.println("Second student's grade in English from 3 years ago:");
2System.out.println(grades[3][1][1]);
3
4System.out.println("First student's grade in Math from this year:");
5System.out.println(grades[0][0][0]);

Chapter Assignment: Gradebook

Instructions: Create a simple Gradebook program. The program will contain a 2D array of Strings. It will be 50x5, so 50 rows and 5 columns. Each row will correspond to the student's ID, starting with zero (so do not create a separate column to store an arbitrary ID). Since there are 50 rows, it supports a maximum of 50 students. Column zero will be their name, 1 will be Math grade, 2 is English grade, 3 is Science grade, and 4 is History grade.

The program will have the following capabilities:

  1. List all students and their grades from the Gradebook
  2. Add a new student, with their name and grade in each subject
  3. Modify an existing student based on their ID number, updating their name and grades.
  4. Calculate the GPA of the student's four grades, as an average.

Assumptions: When entering data, we can assume that the user always types the correct value. There is no need to do extensive error checking or "idiot proofing". The gradeBook may use public/static variables to keep track of student grades, and the number of students in the book. These are not the best practices, but we want to get a functioning gradebook, illustrating that you understand 2D array concepts.

The grades will be stored in String format, so our grade book can contain both student names and their grades. You may convert the grades back to double format by using the following method:

The program will not save any data locally once the program terminates.

1//Convert String to Double
2double aDouble = Double.valueOf(STRING);
Up next · part 12 of 17

Chapter 12: Advanced String Concepts

Strings have been used throughout this series. By now, you should understand that strings hold a series of characters. In this chapter, you will learn more…

Continue reading
Was this guide useful?

Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.

Comments

Found an error? instead, it reaches me faster.

No comments yet. Questions and corrections are welcome.