Hello,
The code initializes a irregular array of integers, prints the length of each row in the array. Then I attempted to print the table[i][j], but I run into an out of bounds exception. In the for loops, the conditional statements are based on the value of table.length, which changes depending upon the row your looking at. I believe this has to do with the out of bounds exception.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3. at hslengthdemoarray2.HSLengthDemoArray2.main(HSLengt hDemoArray2.java:32)
Line 32 is: System.out.print(table[i][j] + " ");
Output: 2d table array: 1 2 3
The program should output the following:
2d table array: 1 2 3 4 5 6 7 8 9
2d table array with the one value changed: 1 66 3 4 5 6 7 8 9
When I turn this into a regular 2d array, where each row has 3 elements, the code runs fine and output is as expected. I think this is because the nested for loop only acknowledges one value of table.length for all of i and j. For example; I thought when i = 0, table[0].length would be 3, in j loop, table.length = 3 based on the i loop. Then, when i = 1, table[1].length = 2, in j loop, table.length = 2 based on the i loop.. On the third step of the outerloop, when i = 2, table[2].length = 4, in j loop, table.length = 3 based on i loop. This appears not to be the case. It appears that table.length either holds a value based on i throughout both for loops or table.length changes based on i and j. It would be good if it only depended on i, I think.
package hslengthdemoarray2; public class HSLengthDemoArray2 { public static void main(String[] args) { int[][] table = { {1,2,3}, {4,5}, {6,7,8,9}, }; // A variable length table. // Print the length of each row within the array. System.out.println("length of table[0] is " + table[0].length); System.out.println("length of table[1] is " + table[1].length); System.out.println("length of table[2] is " + table[2].length); System.out.println(); System.out.print("2d table array: "); for(int i=0; i<table.length; i++) { for(int j=0; j<table.length; j++) { System.out.print(table[i][j] + " "); } } table[0][1] = 66; System.out.print("2d table array with the one value changed: "); for(int i=0; i<table.length; i++) { for(int j=0; j<table.length; j++) { System.out.print(table[i][j] + " "); } } } }