Java - Two-Dimensional Arrays


Advertisements

2D Arrays - Matrices

Up until now, all of our arrays have been one-dimensional arrays. These arrays have had "length", but the "width" (or height) remained as only one cell.

We are now ready to discuss two-dimensional arrays, called matrices (singular: matrix). A matrix resembles a table with rows and columns.

It is possible for arrays to have multiple dimensions. A three dimensional array, for example, has 3 subscripts, where each dimension is represented as a subscript in the array. While it is possible for arrays to have any number of dimensions, most arrays are of one or two dimensions.

Syntax

int[ ][ ] scores = new int [ rows ][ columns ]; 

Declaring a Matrix/Two-Dimensional Array

When you define storage for a matrix (a multi-dimensional array), you must specify that the array has more than one dimension by putting more than one subscript in brackets after the type designation.

Declaration:

Declaration with "null" values:

int[ ][ ] scores = new int [ 4 ] [ 5 ] ;    // Declares a 2-D array


This will create a matrix visually represented like this:

The code int [ 4 ] [ 5 ] indicates that there will be four arrays of ints in the array scores, with 5 ints in each array of ints


Declaration with pre-defined values (filling the two-dimensional array):

int[ ][ ] scores = {  { 20, 18, 22, 20, 16 },
                      { 18, 20, 18, 21, 20 },
                      { 16, 18, 16, 20, 24 },
                      { 25, 24, 22, 24, 25 }   };

Working with Matrices

  • No filling when declared - When an array is created it is automatically filled with a zero (for numerical values), a false (for boolean values) or null (for String values).

  • Filling with user input - When working with two-dimensional arrays (such as accessing, filling, printing, etc.), it is necessary to use nested loops. The outer loop controls the number of rows and the inner loop controls the number of columns.

    // Filling the matrix
    for ( row = 0; row < 4; row ++ ) {
        for ( column = 0; column < 5; column + + ) {     
           scores [ row ][ column ] = Console.readInt("Enter score " + column + "for contestant " + row   );
         }
    }
    
  • Length - Just as a command such as list.length returns the length of a one dimensional array, scores.length will return the number of rows in this two-dimensional array. scores[ i ].length will return the number of columns of the row with subscript i in a two-dimensional array.

Manipulating A Matrix:

Suppose you want to save the information for 30 students and 3 exam grades for each student entered at the keyboard. In addition, you want to find the average (which could be a decimal value) for each student, and then store this average in a fourth column of the same matrix. Remember, you will need to obtain the grades before you can compute the average. Here is one possibility:

import java.io.*;
import BreezyGUI.*;

public class matrixtest {

    public static void main(String[] args) {
        double[][] grades = new double[30][4]; //create memory space for entire matrix

        // Fill the matrix with user input and compute average
        int row, column;
        double sum, average;
        for (row = 0; row < 3; row++) {
            sum = 0;
            for (column = 0; column < 3; column++) {
                grades[row][column] = Console.readDouble("Enter grade " + (column + 1)
                        + "for student " + (row + 1));
                sum = sum + grades[row][column];
            }
            average = sum / 3;
            grades[row][3] = average;
        }
        // Print averages only
        System.out.println("You saved the following averages: ");
        for (row = 0; row < 3; row++) {
            System.out.println("Student " + (row + 1) + ": " + grades[row][3]);
        }
    }
}

Working with Strings:

Create a matrix of String values, fill the matrix by list, and print the matrix. Notice that the "internal" arrays are of differing sizes. Notice how the .length is used to deal with these varying lengths during printing.

public class ArrayOfArraysAnimalDemo {

    public static void main(String[] args) {
        String[][] animals = {
            {"DanaDog", "WallyDog", "JessieDog", "AlexisDog", "LuckyDog"},
            {"BibsCat", "DoodleCat", "MillieCat", "SimonCat"},
            {"ElyFish", "CloieFish", "GoldieFish", "OscarFish", "ZippyFish", "TedFish"},
            {"RascalMule", "GeorgeMule", "GracieMule", "MontyMule", "BuckMule", "RosieMule"}
        };

        for (int i = 0; i < animals.length; i++) {
            System.out.print(animals[ i][ 0] + ": ");
            for (int j = 1; j < animals[ i].length; j++) {
                System.out.print(animals[ i][ j] + " ");
            }
            System.out.println();
        }
    }
}


Advertisements