I'm trying to create a 2 dimensional array (acting as a matrix) and then fill it with either a for or while loop.
Essentially, I'm saying:
int [][] matrix = new int [1][1];
In my mind, this is creating 2 arrays with 2 indexes. I believe this is correct, but hey, I've been wrong before, and I'm no pro at coding.
Now, my nested for loops weren't working (index out of bounds) so I'm simplifying it by using a while loop. When I say simplify, I mean that I'm only trying to fill half of each array.
So I declared:
int row = 0; int col = 0;
then:
while (row < 2) {
System.out.println("Enter x");
matrix [row][col] = reader.nextInt();
row++;
}
Okay so in my mind, this SHOULD be able to fill the 1st index of BOTH arrays. However, I get the dreaded array index out of bounds error. I don't understand why. Isn't it essentially saying:
1st loop, matrix [0][0] = 1xval
2nd loop, matrix [1][0] = 2xval
So here's what happens when I run it:
Enter x
1
Enter x
arrayindexoutofbounds
Maybe I'm making a fool of myself by missing something really easy, but hey, this is a good way to learn. Arrays ALWAYS seem to do this to me. Could someone help me out?
Edited by Alyn, 16 October 2011 - 07:15 PM.
added code tag


Sign In
Create Account

Back to top









