Tom Luna wrote:I've been struggling with how to properly write a method that returns the sum of a given row in a two dimensional array.
I'm trying to figure out how to get the values in the array row, and add them to the total.
This is the code I have at the moment;
You are probably missing this at line 14:
Note that in Java, you don't have multidimensional arrays. You have arrays that can have elements that are themselves arrays that can have elements that are themselves arrays that can ... and so on. In short, you can have nested arrays.
So if you declare int num, then num is a regular int that you can iterate over just as any regular int array.
In your case, values[row] is going to be an int and you can use the same code as you would to iterate over any int:
On line 2 above, you can use a regular for-loop or if you don't need an index variable, a for-each loop would be simpler.
In your loop, you've written
It means, you iterate the lines because you've specified the number of lines (values.length).
But in your case, you need to iterate the columns because you've already known the line (it is the row variable):
Then, your loop will be something like this:
In the body of the loop, you can add up all the values (code written by Chandran for line 14):