// class to demonstrate // multidimensional arrays // command line args public class Array2DDemo { // printing a 2D array of ints public static void print2D(int[][] grid) { // outer loop for rows - length of array of arrays for (int [] row : grid) { // inner loop for cols - length of individual array for (int elt : row) { System.out.print(elt+ " "); } System.out.println(); // newline after row } } // printing a 2D array of strings public static void print2D(String[][] grid) { // outer loop for rows - length of array of arrays for (int i = 0; i < grid.length; i++) { // inner loop for cols - length of individual array for (int j = 0; j < grid[i].length; j++) { System.out.print(grid[i][j]+ " "); } System.out.println(); // newline after row } } // rectangular array example public static void recArrayExample() { int [][] rect = new int[2][4]; // special initialization int [][] rect2 = {{1,2},{3,4},{5,6},{7,8}}; int cnt = 1; // loop initialization for (int i = 0; i < rect.length; i++) { for (int j = 0; j < rect[i].length; j++){ rect[i][j] = cnt++; } } System.out.println("\n Printing 2D array of ints"); print2D(rect); System.out.println("\n Printing 2D array of ints"); print2D(rect2); } // example of jagged 2D array public static void jaggedArrayExample() { // 2D array String grd1[][]; // get space for addresses of 3 String arrays grd1 = new String[3][]; // illegal //grd1 = new String[][3]; //grd1 = new String[][]; // each string array is a different size grd1[0] = new String[1]; grd1[1] = new String[5]; grd1[2] = new String[3]; // special initialization String [][] grd2 = {{"hello"},{"cat", "dog", "pig"},{"red", "green", "blue", "viridian", "sinople"}}; // fill up the array // go from 0 to length-1 of array of arrays for (int i = 0; i < grd1.length; i++) { // go from 0 to length-1 of individual array for (int j = 0; j < grd1[i].length; j++) { // i, j is the coordinate in the array grd1[i][j] = "("+i+", "+j+")"; } } // print the result System.out.println("\n Printing 2D jagged array of strings"); print2D(grd1); System.out.println("\n Printing 2D jagged array of strings"); print2D(grd2); } // main method calls examples public static void main(String[] args) { // check if there were command line arguments if (args != null && args.length > 0) { // if r is argument, just do rectangle example if (args[0].equals("r")) { System.out.println("command line arg: r"); recArrayExample(); // any other argument, just do ragged example } else { System.out.println("command line arg given, not r"); jaggedArrayExample(); } // if no arguments, do both examples } else { System.out.println("no command line args given"); // anonymous 2D array! print2D(new int [][] {{1,2,3,4}, {5}, {6, 7, 8}, {9, 10}}); recArrayExample(); jaggedArrayExample(); } } }