Reputation:
I’m trying to create a representation of the following numbers in a column and row.
Why is my second array not being fully printed out?
Also, the numbers aren’t being printed in a row and column fashion. Why is this?
public class MultidimensionalArrays
{
public static void main(String[] args)
{
//initializes rows and columns
//first box = row, second box = column
int firstarray[][] = {{3, 4, 5, 6,} , {8, 9}};
//System.out.println(firstarray[0][1]) = 9;
//initializes another rows and columns
int secondarray[][] = {{11, 12, 13} , {88} , {100, 200, 300} , {33, 35, 37}};
//displays the 1st array
System.out.println("this is the 1st array: ");
display(firstarray);
System.out.println();
//displays the 2nd array
System.out.println("this is the 2nd array: ");
display(secondarray);
}
//makes a method to display out the arrays
public static void display(int x[][])
{
//makes a for-loop that prints out the row
for(int row = 0; row < x.length; row++)
{
//makes a for-loop that prints out the column
for(int column = 0; column < x.length; column++)
{
//sysouts the rows & columns
System.out.print(x[row][column] + "\t");
}
}
}
}
Error code:
this is the 1st array:
3 4 8 9
this is the 2nd array:
11 12 13 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MultidimensionalArrays.display(MultidimensionalArrays.java:37)
at MultidimensionalArrays.main(MultidimensionalArrays.java:24)
Upvotes: 1
Views: 58
Reputation: 22234
You are using the number of rows to print the columns. These obviously don't match in your test case. Modify like this
//makes a for-loop that prints out the row
for(int row = 0; row < x.length; row++)
{
//makes a for-loop that prints out the column
for(int column = 0; column < x[row].length; column++)
{
//sysouts the rows & columns
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
You should probably also print a new line after each row. I added the code for that.
Upvotes: 2
Reputation: 393846
Your array is not a matrix, so column length is not equal to row length. In fact, different rows have different number of columns, so you must use the individual length of each row.
Try :
for(int row = 0; row < x.length; row++)
{
//makes a for-loop that prints out the column
for(int column = 0; column < x[row].length; column++)
{
//sysouts the rows & columns
System.out.print(x[row][column] + "\t");
}
}
Upvotes: 2