简体   繁体   中英

Using a for loop to iterate through a 2D array

I am attempting to write a loop to iterate through a 2D array and sum each sub-array.

So far my code is as follows:

int[][] data = { { 10, 20 }, { 20, 10 }, { 50, 60 }, { 45, 20 }, { 10, 35 }, { 25, 16 } };
int[] sumOfArrays = new int[5];

    for (int[] i : data) {
        int sum = 0;
        for (int x : i) {
            sum =+ x;
        }
        sumOfArrays[i] = sum;
    }

    System.out.println(sumOfArrays);

This is not possible due to a type mismatch: (i) int[] - int

How can I resolve this?

There are a few problems here. Let's start with the one that bit you the hardest.

for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum =+ x;
    }
    sumOfArrays[i] = sum;
}

Inside the context of these nested loops, i refers to an int[] reference, so you can't use it to index into anything.

In general, when dealing with foreach loops, you generally lose the ability to index into them , so you should use caution when you're attempting to do so.

To get that, you have to introduce a new variable. Also be sure to flip your assignment; you want += instead of =+ , since the former is just assignment to a guaranteed positive value.

int idx = 0;
for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum += x;
    }
    sumOfArrays[idx++] = sum;
}

Next, your array is one element too short - you have six rows but you only allocate room for 5. Fix that size and then the above code will work fine.

You are attempting to treat i as if it were an index, but it's a value -- the int[] row you're currently on.

You can keep a separate index variable that is incremented at the end of the i for loop.

int index = 0;
for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum += x;  // +=, not =+
    }
    sumOfArrays[index] = sum;
    index++;
}

An alternative would be to switch to a "standard" for loop, so you have the index variable defined as part of the for loop, getting the int[] yourself.

Either way, you'll need to use Arrays.toString to print the contents of sumOfArrays at the end of your code.

Additionally, the length of sumOfArrays doesn't match the length of data , so you'll get an ArrayIndexOutOfBoundsException . Try

int[] sumOfArrays = data.length;
    int[][] data = { { 10, 20 }, { 20, 10 }, { 50, 60 }, { 45, 20 }, { 10, 35 }, { 25, 16 } };
    int[] sumOfArrays = new int[data.length];

    for (int i = 0; i < data.length; i++) {
        int sum = 0;
        for (int x : data[i]) {
            sum += x;
        }
        sumOfArrays[i] = sum;
    }

    System.out.println(Arrays.toString(sumOfArrays));

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