2D array in android

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 ie relations[maxrow][0]=label; throws an array from the associated exception. If I use relations[0][0]=label; then the code works fine. Does anyone know what is wrong with this code? Thanks.

+4
source share
3 answers

Yes. maxrow greater than or equal to 500 at the point at which you call relations[maxrow][0] = label;

Check where you increase maxrow and make sure it does not exceed your limit of 500.

+2
source

If relations[maxrow][0]=label; does not work, but relations[0][0]=label; works, then maxrow not 0. Try to print the value of maxrow and see what it is.

I assume that you cut out a piece of code that does something like reset the maxrow value, or that it is accidentally set inside your initialization method.

For writing, you do not need to initialize your values ​​to 0. By default, they are already set to 0. You only need this if you initialized them to a non-zero value.

Excellent Intilator 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 } } 

The results of this:

 C:\Documents and Settings\glow\My Documents>javac Oceanblue.java C:\Documents and Settings\glow\My Documents>java Oceanblue 0 

This does not 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 
+1
source

Something, somewhere, is obviously being updated by maxrow. Try searching for maxrow in your code.

0
source

Source: https://habr.com/ru/post/1347632/


All Articles