Chapter 11: Multidimensional Arrays
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.
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.
//creating a 1D array
int[] myArray = new int[6];
//creating a 2D array 6x4 (total 24 values)
int[][] 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.
public static void main(String[] args) {
//a new three by two array
int[][] studentGrades = new int[3][2];
//the first index for each student, the second for the different values associated with them (id and grade)
studentGrades[0][0] = 432;
studentGrades[0][1] = 92;
studentGrades[1][0] = 433;
studentGrades[1][1] = 75;
studentGrades[2][0] = 435;
studentGrades[2][1] = 88;
//print out the student ids and their grades
for(int i = 0; i < 3; i++){
System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "%");
}
}
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,
//a new three by four
int[][] studentGrades = new int[3][4];
//the first index can hold the student's id number, the second, their grade.
studentGrades[0][0] = 432;
studentGrades[0][1] = 92;
studentGrades[0][2] = 87;
studentGrades[0][3] = 97;
studentGrades[1][0] = 433;
studentGrades[1][1] = 75;
studentGrades[1][2] = 80;
studentGrades[1][3] = 96;
studentGrades[2][0] = 435;
studentGrades[2][1] = 88;
studentGrades[2][2] = 92;
studentGrades[2][3] = 69;
//print out the student ids and their grades
for(int i = 0; i < 3; i++){
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.");
}
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:
Student with id: 432 has an average grade of: 92.0% Student with id: 433 has an average grade of: 83.66666666666667% Student with id: 435 has an average grade of: 83.0%View Solution
//iterate through each student
for(int i = 0; i < studentGrades.length; i++){
double average = 0;
//find sum of their grades
for(int x = 1; x< studentGrades[0].length; x++){
average += studentGrades[i][x];
}
//find and print average
average = average / 3;
System.out.println("Student with id: " + studentGrades[i][0] + " has an average grade of: " + average + "%");
}
Shorthand Syntax
Recall that a 1D array can be declared, initialized, and populated with values using this shorthand syntax:
int[] 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.
int[][] 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.
//this array is functionally equivalent
int[][] anotherArray = {{5,10,15},{10,20,30}};
//to this array
int[][] anArray = new int[2][3];
anArray[0][0] = 5;
anArray[0][1] = 10;
anArray[0][2] = 15;
anArray[1][0] = 10;
anArray[1][1] = 20;
anArray[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.
int[][] anotherArray = {
{5,10,15},
{10,20,30}
};
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.
Name | Fav Color | Fav Food | Fav Place |
Jack | Violet | Tacos | Beach |
Sammy | Black | Sushi | New York |
Joey | Green | Steak | Japan |
Sample Output:
|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.
public class Main {
public static void main(String[] args) {
//Create the Array
String studentData[][] = {
//data here
};
tablePrinter(studentData);
}
/**
* @param arr The array being printed to the screen in a nicely formatted manner
*/
public static void tablePrinter(String[][] arr) {
}
}
View Solution
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
//Create the Array
String studentData[][] = {
{"Name ", "Fav Color", "Fav Food", "Fav Place"},
{"Jack ", "Violet ", "Tacos ", "Beach "},
{"Sammy", "Black ", "Sushi ", "New York "},
{"Joey ", "Green ", "Steak ", "Japan "}
};
tablePrinter(studentData);
}
/**
* @param arr The array being printed to the screen in a nicely formatted manner
*/
public static void tablePrinter(String[][] arr) {
//iterate through the rows
for (int row = 0; row < arr.length; row++) {
//print the first vertical bar
System.out.print("|");
//iterate through the columns
for (int col = 0; col < arr[0].length; col++) {
//print the contents of each column, followed by a vertical bar
System.out.print(arr[row][col]);
System.out.print("|");
}
System.out.println();
}
}
}
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.
//a 3x4x4 array
int[][][] 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.
int grades[][][] = {
//year zero
{ //student 0 student 1 student 2
{89,95,85,93},{99,82,95,90},{91,87,90,77}
},
//year one
{ //student 0 student 1 student 2
{90,90,88,90},{92,87,86,89},{95,95,90,87}
},
//year two
{ //student 0 student 1 student 2
{90,80,90,75},{85,81,79,81},{99,98,90,89}
},
//year three
{ //student 0 student 1 student 2
{92,82,81,78},{89,81,74,85},{97,85,89,90}
}
};
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.
System.out.println("Second student's grade in English from 3 years ago:");
System.out.println(grades[3][1][1]);
System.out.println("First student's grade in Math from this year:");
System.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:
- List all students and their grades from the Gradebook
- Add a new student, with their name and grade in each subject
- Modify an existing student based on their ID number, updating their name and grades.
- 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.
//Convert String to Double
double aDouble = Double.valueOf(STRING);
View Starter Code
Use the following template to get started.
Starter Codeimport java.util.Scanner;
public class Main {
//the gradeBook array will be 50x5, supporting up to 50 students with their name, english, math, science, and history grades (in that order).
static String[][] gradeBook = new String[50][5];
//keep track of total number of students in the system
static int numStudents = 0;
//For reading user input later in the program
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Gradebook.");
//Make the decision(s)
makeDecision();
System.out.println("Program terminating. All data is lost.");
userInput.close();
}
/**
* Allows the user to select what to do next
*/
public static void makeDecision() {
System.out.println("\nPlease select an option.");
System.out.println("0) Exit the program.");
System.out.println("1) List all students and grades");
System.out.println("2) Add new student and grades");
System.out.println("3) Modify individual student");
System.out.println("4) Calculate individual student GPA.");
int selection = userInput.nextInt();
if (selection == 0) {
return;
} else if (selection == 1) {
listAllGrades();
} else if (selection == 2) {
addNew();
}
else if (selection == 3) {
modifyStudent();
}
else if (selection == 4){
calcGPA();
}
else{
System.out.println("Invalid selection entered.");
makeDecision();
}
}
/**
* List all the recorded grades in the gradeBook
*/
public static void listAllGrades() {
System.out.println("-- Student Grades Report --");
//TODO Iterate through the grades in the gradebook, printing their result by calling the printStudent method.
//Go back to makeDecision
makeDecision();
}
/**
* Add a new student to the book, as a new row in the "table"
*/
public static void addNew(){
//TODO - Add code using Scanner to record the next student's information into the Array
//The first index of gradeBook array should be [numStudents], this is the NEXT row being added to the array.
//Increment numStudents by 1 when done, so the next index comes after this one
//Go back to makeDecision
makeDecision();
}
/**
* Modify an existing student given their ID
*/
public static void modifyStudent(){
System.out.println("-- Modify Student --");
System.out.println("Enter Student ID: ");
//TODO: Get the student's ID using scanner
//TODO: Modify the student's information (Have them re-enter all 5 values)
makeDecision();
}
/**
* Print out a student's information
* @param studentID - The ID of the student being printed
*/
public static void printStudent(int studentID){
//TODO: Print out the student's details in a nicely formatted String
}
/**
* Calculate the student's GPA by adding all 4 grades together, and dividing by 4.
* You may use Double.valueOf(STRING) to get the double value of a String.
*/
public static void calcGPA(){
System.out.println("Enter the student's ID:");
//TODO: Get the student ID entered
//Calculate the GPA. Print out the student's name and their GPA.
makeDecision();
}
}
Sample Output:
Welcome to Gradebook. Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 2 -- Add a new student -- What is their name? Kevin What is their Math grade? 87 What is their English grade? 79 What is their Science grade? 98 What is their History grade? 78 Student added with these properties: ID: 0 Name: Kevin Grades - Math: [87] English: [79] Science: [98] History: [78] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 3 -- Modify Student -- Enter Student ID: 0 Modifying Kevin Enter new name: Kevin Enter new Math grade? 65 Enter new English grade? 76 Enter new Science grade? 87 Enter new History grade? 97 Student has been updated with these details: ID: 0 Name: Kevin Grades - Math: [65] English: [76] Science: [87] History: [97] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 4 Enter the student's ID: 0 Kevin has a GPA of 81.250000 Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 2 -- Add a new student -- What is their name? Jackie What is their Math grade? 76 What is their English grade? 87 What is their Science grade? 68 What is their History grade? 98 Student added with these properties: ID: 1 Name: Jackie Grades - Math: [76] English: [87] Science: [68] History: [98] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 0 Program terminating. All data is lost. Process finished with exit code 0
Solution:
Here is a sample solution to this project. Note that there are other ways to complete this project. As long as you properly handled the array and all the functions work as described, you have completed this project successfully.
Possible Solution
import java.util.Scanner;
public class Main {
//the gradeBook array will be 50x5, supporting up to 50 students with their name, english, math, science, and history grades (in that order).
static String[][] gradeBook = new String[50][5];
//keep track of total number of students in the system
static int numStudents = 0;
//For reading user input later in the program
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Gradebook.");
//Make the decision(s)
makeDecision();
System.out.println("Program terminating. All data is lost.");
userInput.close();
}
/**
* Allows the user to select what to do next
*/
public static void makeDecision() {
System.out.println("\nPlease select an option.");
System.out.println("0) Exit the program.");
System.out.println("1) List all students and grades");
System.out.println("2) Add new student and grades");
System.out.println("3) Modify individual student");
System.out.println("4) Calculate individual student GPA.");
int selection = userInput.nextInt();
if (selection == 0) {
return;
} else if (selection == 1) {
listAllGrades();
} else if (selection == 2) {
addNew();
}
else if (selection == 3) {
modifyStudent();
}
else if (selection == 4){
calcGPA();
}
else{
System.out.println("Invalid selection entered.");
makeDecision();
}
}
/**
* List all the recorded grades in the gradeBook
*/
public static void listAllGrades() {
System.out.println("-- Student Grades Report --");
if( numStudents == 0){
System.out.println("There are no students in the database. Please add them.");
}
else{
//loop through students and print them out
for(int i = 0; i < numStudents; i++){
printStudent(i);
}
}
makeDecision();
}
/**
* Add a new student to the book, as a new row in the "table"
*/
public static void addNew(){
System.out.println("-- Add a new student --");
System.out.println("What is their name?");
gradeBook[numStudents][0] = userInput.next();
System.out.println("What is their Math grade?");
gradeBook[numStudents][1] = userInput.next();
System.out.println("What is their English grade?");
gradeBook[numStudents][2] = userInput.next();
System.out.println("What is their Science grade?");
gradeBook[numStudents][3] = userInput.next();
System.out.println("What is their History grade?");
gradeBook[numStudents][4] = userInput.next();
System.out.println("Student added with these properties:");
printStudent(numStudents);
numStudents ++;
makeDecision();
}
/**
* Modify an existing student given their ID
*/
public static void modifyStudent(){
System.out.println("-- Modify Student --");
System.out.println("Enter Student ID: ");
int studentID = userInput.nextInt();
if(studentID >= 0 && studentID < numStudents){
System.out.printf("\nModifying %s\n", gradeBook[studentID][0]);
System.out.println("Enter new name:");
gradeBook[studentID][0] = userInput.next();
System.out.println("Enter new Math grade?");
gradeBook[studentID][1] = userInput.next();
System.out.println("Enter new English grade?");
gradeBook[studentID][2] = userInput.next();
System.out.println("Enter new Science grade?");
gradeBook[studentID][3] = userInput.next();
System.out.println("Enter new History grade?");
gradeBook[studentID][4] = userInput.next();
System.out.println("Student has been updated with these details:");
printStudent(studentID);
}
else{
System.out.println("No student exists with this ID.");
}
makeDecision();
}
/**
* Print out a student's information
* @param studentID - The ID of the student being printed
*/
public static void printStudent(int studentID){
System.out.printf("\nID: %d Name: %s Grades - Math: [%s] English: [%s] Science: [%s] History: [%s]", studentID, gradeBook[studentID][0], gradeBook[studentID][1], gradeBook[studentID][2], gradeBook[studentID][3], gradeBook[studentID][4]);
}
/**
* Calculate the student's GPA by adding all 4 grades together, and dividing by 4.
* You may use Double.valueOf(STRING) to get the double value of a String.
*/
public static void calcGPA(){
System.out.println("Enter the student's ID:");
int studentID = userInput.nextInt();
//Check if this ID is between 0 and the number of students total
if(studentID >= 0 && studentID < numStudents) {
double GPA = 0;
GPA = Double.valueOf(gradeBook[studentID][1]) + Double.valueOf(gradeBook[studentID][2]) + Double.valueOf(gradeBook[studentID][3]) + Double.valueOf(gradeBook[studentID][4]);
GPA = GPA / 4;
System.out.printf("\n%s has a GPA of %f", gradeBook[studentID][0], GPA);
}
else{
System.out.println("No student exists with this ID.");
}
makeDecision();
}
}
Go To Chapter 12: Advanced Strings