OOB例外。如何调试?
int sum[]= new int[4], ctr = 0, sums=0;
for(int row=0;row<x.length;row++){
int col = 0;
for(int column=0;column<x[row].length;column++){
sum[row] += x[row][column];
sums += x[row][column];
col += x[column][row];
}
ctr++;
System.out.println("The sum of column " + ctr +": " + col);
System.out.println("The sum of row " + ctr +": " + sum[row]);
}
System.out.println("The sum of all arrays: "+sums);
}
}
这是代码。问题出在col += x[column][row];
我被困了,请帮忙。感谢
答案 0 :(得分:1)
下面:
for(int column=0;column<x[row].length;column++){
sum[row] += x[row][column];
sums += x[row][column];
col += x[column][row];
}
您拥有的行数多于列数。
这样做是为了抓住它:
for(int column=0;column<x[row].length;column++){
sum[row] += x[row][column];
sums += x[row][column]
if (row < x[row].length){
col += x[column][row];
}
}
答案 1 :(得分:0)
只需在代码中添加此行
即可 System.out.println(column+" "+row);
col += x[column][row];
运行代码后......最后,row
值变为3
因此x[0][3]
会给你OOB异常。
您必须在某种情况下处理col += x[column][row];
,以便在行超过值3时永远不会执行