我试图使用eclips在android中运行这段代码。
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;最后一行即relations[maxrow][0]=label;是抛出绑定异常的数组。如果我使用relations[0][0]=label;,那么代码运行良好。有谁知道这段代码有什么问题吗?谢谢。
发布于 2011-04-11 21:12:11
是。在调用maxrow的点上,relations[maxrow][0] = label;大于或等于500
检查增量maxrow的位置,并确保它不会超出或等于您的限制,500。
发布于 2011-04-11 21:12:17
如果relations[maxrow][0]=label;失败,但relations[0][0]=label;有效,那么maxrow不是0。试着打印出maxrow的值,看看它是什么。
我的猜测是,您已经剪掉了执行重置maxrow值等操作的代码片段,或者在您的初始化方法中意外地设置了它。
为了记录在案,您不需要将值初始化为0。默认情况下,它们已经设置为0。只有在将它们初始化为非零值时,才需要这样做。
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;
}
}海洋蓝的例子:
// 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
}
}这次会议的结果如下:
C:\Documents and Settings\glow\My Documents>javac Oceanblue.java
C:\Documents and Settings\glow\My Documents>java Oceanblue
0这不管用:
// 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
}
}结果,正如你提到的
C:\Documents and Settings\glow\My Documents>javac Oceanblue.java
Oceanblue.java:4: variable test might not have been initialized
test++; // bombs
^
1 error发布于 2011-04-11 21:14:08
某个地方显然正在更新maxrow。尝试搜索代码中的maxrow。
https://stackoverflow.com/questions/5627580
复制相似问题