[英]Summing cells from table
I seem to not be able to solve this java.lang.ArrayIndexOutOfBoundsException: 5
我似乎无法解决此
java.lang.ArrayIndexOutOfBoundsException: 5
I understand the error, but the table is 5x5 and I think I have everything right for printing it. 我理解错误,但是表格是5x5,我认为我有一切权利打印它。
public static int tulosta_matriisi(int[][] matriisi) {
int i=0, j=0;
for(i = 0; i <= 4; i++) {
for(j = 0; j <= 4; j++) {
if(j == 4 && i <= 4)
System.out.println(matriisi[i][j]);
else if(i <= 4 && j <= 4)
System.out.print(matriisi[i][j] +"\t");
}
}
return matriisi[i][j];
}
To avoid all this problem you have to use : 为了避免所有这些问题,您必须使用:
for(i = 0; i < matriisi.length; i++) {
for(j = 0; j < matriisi[i].length; j++) {
...
When you get out your loop, the i and j will be incremented so you should not return matriisi[i][j]
this make this error java.lang.ArrayIndexOutOfBoundsException: 5
, so instead you should to return matriisi[i-1][j-1]
so in the end your program should look like this : 当您退出循环时,i和j将增加,因此您不应返回
matriisi[i][j]
这会导致此错误java.lang.ArrayIndexOutOfBoundsException: 5
,因此您应返回matriisi[i-1][j-1]
因此,最后您的程序应如下所示:
public static int tulosta_matriisi(int[][] matriisi) {
int i = 0, j = 0;
for (i = 0; i < matriisi.length; i++) {
for (j = 0; j < matriisi[i].length; j++) {
if (j == matriisi[i].length - 1 && i <= matriisi.length) {
System.out.println(matriisi[i][j]);
} else if (i <= matriisi.length && j <= matriisi[i].length) {
System.out.print(matriisi[i][j] + "\t");
}
}
}
return matriisi[i - 1][j - 1];
}
Good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.