Wednesday, 17 December 2014

// The "MultiDimensionalArraysExample2" class.  Page 320 (bottom).
// Example 2.  (from the Carter book)

// Suppose we want to create a table with 3 rows and 4 columns, initialized
// as shown at the bottom of page 320.
// We can do this by declaring and intializing the "scores" array, as follows:

public class MultiDimensionalArraysExample2
{
    public static void main (String[] args)
    {
        int[] [] scores = {{5, 2, 7, 3},
                {6, 8, 7, 9},
                {4, 5, 2, 3}};

        // On the right side of the assignment statement, the elements of each row
        // of the array are enclosed by brace brackets and separated by commas.
        // Similarly, the sets of values for each row are themselves enclosed by
        // brace brackets and separated by commas.  The statement could have been
        // written all on one line, but we wrote it so that to make the structure of
        // the array called "scores" clearer to a human reader.
        // to view the element values of the "scores" array the way they appear
        // above, we should do this:

        for (int i = 0 ; i < scores.length ; i++)
        {
            System.out.println (); // a return makes one line of values per row
            for (int j = 0 ; j < scores [0].length ; j++)
            {
                System.out.print (scores [i] [j] + " ");
            } // end of inner for loop
        } // end of outer for loop

        // The 1-dimensional arrays that compose a 2-dimensional array need not all
        // be of the same length, as the next example (3) illustrates.

    } // main method
} // MultiDimensionalArraysExample2 class

No comments:

Post a Comment