简体   繁体   中英

Finding the Sum of a Jagged Array

*Homework

I'm trying to add the values in an array. With the sum method I wrote below, the program only works for arrays that are not jagged. If I test a jagged array, I get an IndexOutOfBoundsException. What's the next step I should take to try and make this method work if the array is jagged?

int sum() {
    int sum = 0;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            sum += array[j][i];
        } 
    }
return sum;
}

Your method is close, but it has a small bug - this

sum += array[j][i];

should be

sum += array[i][j];

Note that your inner loop is iterating over array[i] .

反转索引:

sum += array[i][j];

You are mixing indexes. You are first looping through rows ( i ) , then through columns ( j ), but when you access to the array elements, you are using j for the rows and i for the columns.

It should be:

sum += array[i][j];

Change

sum += array[j][i];

to

sum += array[i][j];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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