[英]Out of bounds exception on simple nested for loop using rectangular array
我有一個簡單的嵌套的for循環,可以完美地輸出結果,然后拋出:
線程“主”中的異常java.lang.ArrayIndexOutOfBoundsException:4
該數組是4行和4列,我試圖對列進行總計,所以我基本上只是反轉了嵌套循環。
rowIndex = 1;
for (int i = 0; i < regions[i].length; i++)
{
int sum = 0;
for (int j = 0; j < regions.length; j++)
{
sum += regions[j][i];
}
System.out.println("Q" + rowIndex + ": " + currency.format(sum));
rowIndex++;
}
這不應該看起來像...
rowIndex = 1;
for (int j = 0; j < regions.length; j++) // here regions.length
{
int sum = 0;
for (int i = 0; i < regions[j].length; i++) // here index j
{
sum += regions[j][i];
}
System.out.println("Q" + rowIndex + ": " + currency.format(sum));
rowIndex++;
}
認為您混合了指標...干杯!
您搞砸了數組的索引。 我猜你的代碼應該是這樣的:
rowIndex = 1;
for (int i = 0; i < regions.length; i++)
{
int sum = 0;
for (int j = 0; j < regions[i].length; j++)
{
sum += regions[i][j];
}
System.out.println("Q" + rowIndex + ": " + currency.format(sum));
rowIndex++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.