I am essentially trying to create a 2 x 10 2d array that replaces the first row with 0 but every time I run it only gives me the first two values. I'm fairly certain it's correct but I want the whole array to also display the values I put in. I'm still relatively new to Java and would like to know how I could fix this. Thanks! CODE
public class QuestionTwo { public static void main(String[] args) {
int[][] table = { {20, 16}, {1, 23}, {9, 46}, {73, 8}, {95, 18}, {67, 0}, {13, 24}, {36, 69}, {21, 55}, {48, 56}
};
for (int c =0; c < 2; c ) {
for (int r=0; r < 10; r ) {
table[r][c] = 0;
System.out.println(table[c][r]);
}
}
}
}
CodePudding user response:
You have a 10 element array of two element arrays.
Your outer loop goes from 0 to 1, and your inner loop goes from 0 to 9. Your inner loop is iterating over 2-element arrays and when you reach 2 it get's out of bounds exception trying to access 3rd element of 2 element array.
You need to switch your iterators around so that you first iterate 0-9 and inner goes 0-1.
CodePudding user response:
Because you are doing it the other way round.
int[][] myArray = {{0,0}, {0,0}, {0,0}, {0,0}};
results in an array like this int[4, 2], and you are iterating like if it were int[2, 4]. Swap the iteration values.
