Reputation: 987
I am trying to run this code in android using eclips IDE.
int maxrow=0;
int label=10;
int[][] relations=new int[500][200];
make2dzero(relations,500,200); //initialized every element with 0.
relations[maxrow][0]=label;
The last line i.e relations[maxrow][0]=label;
is throwing an array out of bound exception. If i use relations[0][0]=label;
then the code runs fine.
Does any one know what is wrong with this piece of code? Thanks.
Upvotes: 4
Views: 16853
Reputation: 82559
if relations[maxrow][0]=label;
fails, but relations[0][0]=label;
works, then maxrow
is not 0. Try printing out the value of maxrow
and seeing what it is.
My guess is you have snipped out the piece of the code that does something like reset the value of maxrow
, or it's accidentally being set inside your initialization method there.
For the record, you don't need to initialize your values to 0. They're already set to 0 by default. You'd only need that if you were initializing them to a non-zero value.
Superior intializer for OP:
/**
* Initialize a 2d int array to any single value
* The array does not need to be rectangular.
* Null rows in the 2d array are skipped (code exists to initialize them to empty.)
* @param arr the array to modify to contain all single values
* @param value the value to set to all elements of arr
*/
static void initializeArray(final int[][] arr, final int value) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) continue; // perhaps it wasn't initialized
/* optional error handling
if(arr[i] == null) {
arr[i] = new int[0];
continue;
}
*/
for(int j = 0; j < arr[i].length; j++) arr[i][j] = value;
}
}
Examples for Oceanblue:
// works, arrays as OP is working with
class Oceanblue {
public static void main(String[] args) {
int[][] arr = new int[30][50];
System.out.println(arr[4][6]); // should be 0
}
}
Results of the this one:
C:\Documents and Settings\glow\My Documents>javac Oceanblue.java
C:\Documents and Settings\glow\My Documents>java Oceanblue
0
This doesn't work:
// doesn't work for local variables that aren't arrays
class Oceanblue {
public static void main(String[] args) {
int test;
test++; // bombs
System.out.println(test); // should be 1, but line above bombed
}
}
Result, as you mentioned
C:\Documents and Settings\glow\My Documents>javac Oceanblue.java
Oceanblue.java:4: variable test might not have been initialized
test++; // bombs
^
1 error
Upvotes: 1
Reputation: 9248
Something, somewhere is obviously updating maxrow. Try searching on maxrow in your code.
Upvotes: 0
Reputation: 26271
Yes. maxrow
is greater than or equal to 500 at the point in which you call relations[maxrow][0] = label;
Check where you increment maxrow
and make sure it doesn't go beyond or equal to your limit, 500.
Upvotes: 2