//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author Casey Bowman * @version 1.1 * @date Mon Mar 02 14:14:06 EST 2015 * @see (License) MIT style license */ import java.util.Arrays; //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Class that creates a two-dimensional integer array and sets the values: * [ 1, 2, 3, 4, 5 ] * [ 6, 7, 8, 9, 10] * [ 11, 12, 13, 14, 15] * [ 16, 17, 18, 19, 20] * [ 21, 22, 23, 24, 25] */ public class DoubleForLoop { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Main method. Calls three functions: * 1. initArray (int, int) - initializes the double array and populates * it with values. * 2. printArray1 (int[][]) - prints the array by iterating through both * dimensions appropriately. * 3. printArray2 (int[][]) - prints the array by iterating through just * the rows and using the toString method of * class Arrays to print each row array. */ public static void main (String[] args) { int rows = 5; int cols = 5; int[][] nums = initArray (rows, cols); printArray1 (nums); System.out.println (); printArray2 (nums); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Array initializiation method. Populates the array with the appropriate * values * @param rows the number of rows in the array. * @param cols the number of columns in the array. */ public static int[][] initArray (int rows, int cols) { int[][] c = new int[rows][cols]; int count = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { c[i][j] = count; count++; } } return c; } // initArray //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Array printing method. Prints by iterating through the entire array * @param c the double array being printed */ public static void printArray1 (int[][] c) { for (int i = 0; i < c.length; i++) { System.out.print ("["); for (int j = 0; j < c[0].length; j++) { if (j < c[0].length - 1) System.out.print (c[i][j] + ", "); else System.out.println (c[i][j] + "]"); } } } // printArray1 //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Array printing method. Prints using the toString method of class Arrays * @param c the double array being printed */ public static void printArray2 (int[][] c) { for (int i = 0; i < c.length; i++) System.out.println (Arrays.toString (c[i])); } // printArray2 } // DoubleForLoop