-2

I am trying to sum all the int values of a 2D array. I named it array. my function is then called arraySum. If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.

int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) { 
    if (array == null) {  // test if the incoming param is null
        return 0;
    } else { 
        for (int i = 0; i < array.length; i++) {  // length of the outer array
            for (int j = 0; j < array[i].length; j++) {  // length of the inner array
                sum += array[i][j];
            }
        }
        return sum;  // moved out of the loop
    }
} 

my error message:

java.lang.AssertionError: Incorrect result:  expected [-217085] but found [-308126] 


badatjava
  • 1
  • 1
  • *java.lang.AssertionError: Incorrect result: expected [-217085] but found [-308126]* - this is not being output from the code that is shown above, but one guess is that the sum value is exceeding the max/min values that can be stored in a `int` - try using a `long` instead. – Scary Wombat Feb 12 '20 at 05:20
  • now i am getting "incompatible types: possible lossy conversion from long to int" after i changed every int to a long. was i supposed to only change some ints to longs?...i just don't know what else i can do.... – badatjava Feb 12 '20 at 05:33
  • Before posting every single error that you find try searching for it yourself. e.g. https://stackoverflow.com/questions/23748942/possible-lossy-conversion-from-long-to-int – Scary Wombat Feb 12 '20 at 05:36
  • i know that this error means something is lost between the conversion between the two types, but i just don't understand how it applies to this when i get rid of the int. i would think that it doesn't matter about the conversion because int should be out of the picture. this question is due in 14 minutes, so i'm giving up soon... – badatjava Feb 12 '20 at 05:47
  • i read it, but couldn't figure out a cast in time...thanks for everything – badatjava Feb 12 '20 at 06:01

3 Answers3

1
  1. Fixing the method signature is the first step.
  2. Then you'll need to fix the null check.
  3. Then your loops need to check the size of the inner and outer arrays.
  4. Move the return statement.

Here's the fixed code:

static int arraySum(int[][] array) {  // fix the signature
    if (array == null) {  // test if the incoming param is null
        return 0;
    } else { 
        int sum = 0;  // you need this in the scope of the method - it will be returned at the end
        for (int i = 0; i < array.length; i++) {  // length of the outer array
            for (int j = 0; j < array[i].length; j++) {  // length of the inner array
                sum += array[i][j];
            }
        }
        return sum;  // moved out of the loop
    }
}

Edit: I've concentrated on just the method now - how you call it is up to you. Please note that the method will not affect any externally defined sum variable. It will return the sum and it's up to the caller to store that value somewhere.

Jason
  • 11,744
  • 3
  • 42
  • 46
  • it says it can't the symbols i or j, but I am unsure as to how I could initialize them...it also says "non-static variable sum cannot be referenced from a static context" with reference to "sum"....I have no idea what that means. Do you? – badatjava Feb 12 '20 at 04:37
  • int[][] array = new int[i][j]; won't work with i and j not declared at that scope, as noted by @scarywombat. And that error message says that int sum, which is a member variable of a particular instance of the object cannot be messed with from a static method which need not even have an instance of the object around to run. – Jeremy Kahan Feb 12 '20 at 05:07
0

Avoid using primitive for statement. See following:

    static int arraySum(int[][] array) {
        int sum = 0;
        if (array == null) return 0;

        for(int[] row: array){
            for(int col : row) {
                sum += col;
            }
        }
        return sum;
    }
royalghost
  • 2,773
  • 5
  • 23
  • 29
  • I am new to Java, so this doesn't really make sense...is it an enhanced for-loop? I did not know enhanced for-loops could be used on arrays... – badatjava Feb 12 '20 at 04:39
  • Yes, that is an enhanced for loop. It can be very helpful with 2D arrays (less thinking about indices). – Jeremy Kahan Feb 12 '20 at 05:03
0

Streams can do this too:

//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}}; 

//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum(); 

System.out.println(sum);

Picking apart the summing code:


Stream.of(array)

Turns the 2D array of type int[][] into a Stream<int[]>. From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.

So at this point we'll have a stream that contains:

  • an int[] array containing {1,2,3}
  • an int[] array containing {4,5}
  • an int[] array containing {6}

.flatMapToInt(IntStream::of)

So far we have a Stream of int[], still two-dimensional. Flat map flattens the structure into a single stream of ints.

flatMapToInt() expands each int[] element of the stream into one or more int values. IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values.

After the flattening, we'll have an int stream of:

{1,2,3,4,5,6}


.sum()

Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.


Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced. I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.

prunge
  • 22,460
  • 3
  • 73
  • 80
  • I am new to Java, so this isn't really clicking with me right now. also, for the problem i am supposed to create a function, which i believe this does not do. i hope someone more advanced finds this and is able to learn from it. – badatjava Feb 12 '20 at 05:25