Exception in main thread for 2D Array (columns)
Hello everyone I am very new to Java programming and need help with this program. I need to print a list of numbers by columns instead of rows i.e. for the table: 10 12 13 14 I need to print 10, 15, 19, 12, 16, etc. instead of 10, 12, 13, 14, etc.
15 16 17 18
19 20 21 22
BUT I keep getting an exception in main thread error. The exact error message after I compile it is: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Assign7.main<Assign7.java:12>
Yes I am in a class but I'm allowed to ask for help outside of the classroom.
Code Java:
public class Assign7 {
public static void main(String args[]) {
int[][] intar = {
{ 10, 12, 13, 14 },
{ 15, 16, 17, 18 },
{ 19, 20, 21, 22 }
};
for (int row = 0; row < intar.length; row++)
{
for (int col = 0; col < intar[row].length; col++)
System.out.println(intar[col][row]);
}
}
}
Re: Exception in main thread for 2D Array (columns)
Look closely at how you have defined your array to represent rows and columns, then look at how you are looping over and then accessing the row and column (in particular look at the very line the exception is being thrown). Write this out on paper if you have to, as this sometimes helps.
Re: Exception in main thread for 2D Array (columns)
Thanks for the suggestion!