简体   繁体   English

使用矩形数组的简单嵌套for循环上的越界异常

[英]Out of bounds exception on simple nested for loop using rectangular array

I have a simple nested for loop that outputs the results perfectly but then throws a: 我有一个简单的嵌套的for循环,可以完美地输出结果,然后抛出:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:4

The array is 4 rows and 4 columns, and I am trying to total the columns so I basically just reversed the nested loop. 该数组是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++;
        }

Shouldn't this rather look like ... 这不应该看起来像...

    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++;
    }

Think you mixed up the indices ... Cheers! 认为您混合了指标...干杯!

You are messing up the indices of array. 您搞砸了数组的索引。 I Guess your code should be something like this: 我猜你的代码应该是这样的:

   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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM