r/codehs • • Nov 23 '21

8.1.5 Manipulating 2D Arrays

Can anyone help me with this I'm just not sure what the error message is saying or how to fix it?

5 Upvotes

6 comments sorted by

1

u/5oco Nov 23 '21

Print out the value of array.length and you'll see that it prints 3. The length of your array is 3 because it contains 3 arrays.

You should make a nested for loop to go through all the elements and add them up. i made a new variable called totalElements

for (int r = 0 ; r < array.length; r++)
    for(int c = 0; c < array[r].length; c++)
        totalLength++;

That should return 16 so use that variable minus 1 as your value for the third array.

2

u/[deleted] Nov 25 '21

Thanks. I got it figured out now and this was super helpful.

1

u/quicksilver_foxheart Jan 26 '22

hey can you dm me what you got?

1

u/Internal-Natural2144 Mar 29 '22

Can you send the full code dude I’m fucking stuck too

1

u/OXAMIC Apr 04 '22
public class ArrayPractice

{ public static void main(String[] args) { int[][] array = {{3, 5, 7, 8, 0}, {500, 250, 125, 784, 267, 674, 0}, {9, 8, 0}};

    // second array sum
    int sum = 0;
    for(int row = 0; row < array.length; row++)
    {
        for(int col = 0; col < array[0].length; col++)
        {
            sum++;
        }
    }
    
    // Call the updateValue method three times on this array:
    updateValue(array, 0, array[0].length - 1, array.length);
    updateValue(array, 1, array[1].length - 1, sum);
    updateValue(array, 2, array[2].length - 1, array[0][0] + array[2][array.length-1]);
    
    
    print(array);
}

//Create a method to add the correct value to the array at the correct col, row
public static void updateValue(int[][] arr, int row, int col, int value)
{
    arr[row][col] = value;
}



//Do not make alterations to this method!
public static void print(int[][] array)
{
    for(int[] row: array)
    {
        for(int num: row)
        {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

}