Wednesday, 17 December 2014

// The "MultiDimensionalArraysExample4" class.  Page 321-322.
// Example 4.  (from the Carter book)

// Array declarations, like the one in Example 3 ("triTable"),
// in which the second (column) dimension's size is unspecified,
// are legal.  However, it is not legal to have the first (row)
// dimension's size unspecified.  For example, look at this
// illegal declaration, as follows:

public class MultiDimensionalArraysExample4
{
    public static void main (String[] args)
    {
        //int [] [] badArray = new int [] [20];
        //
        // this declaration is not permitted. During compilation, the error
        // message will read: "Expression expected after this token"
        // --> meaning that the first (row) dimension must have a size
        // specified inside the first [].
        //
        // Non-rectangular 2-dimensional arrays are sometimes
        // called "ragged arrays".  We can initialize ragged
        // arrays in their declarations, just as we did for
        // rectangular arrays, as follows:

        int[] [] ragged = {{4, 3, 7},
                {5, 2},
                {7, 8, 1, 4}};

        // this declaration creates the array called "ragged" whose
        // length of each row may be different, which we can see, as follows:

        for (int row = 0 ; row < ragged.length ; row++)
        {
            System.out.println ();
            // "col" may not vary at the same rate as "row" -->
            // (there could be more, less, or the same col length
            //  compared to row length)
            for (int col = 0 ; col < ragged [row].length ; col++)
            {
                System.out.print (ragged [row] [col] + " ");
            } // end of inner for loop
        } // end of outer for loop

        System.out.println ();

    } // main method
} // MultiDimensionalArraysExample4 class

No comments:

Post a Comment