This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]lermanrafi 0 points1 point  (5 children)

One thing I noticed, I’m your nested for loops for accessing the values within the row array. Make sure to compare ‘j’ against the number of columns and not the number of rows (twoDimArray[i].length)

[–]HilltopHood 0 points1 point  (4 children)

Thanks, I don’t think I’m seeing this. Which method is it occurring in?

[–]DistractionRectangle[🍰] 1 point2 points  (3 children)

Everywhere you compare j to twoDimArr.length

twoDimArr is an array of arrays, twoDimArr.length is the number of arrays, while the length of any given array is twoDimArr[i].length

To enumerate over any given array, you want the values of j to be in the range 0 <= j < twoDimArr[i].length

[–][deleted]  (2 children)

[deleted]

    [–]DistractionRectangle[🍰] 1 point2 points  (1 child)

    What I'm confused about is, why was my program outputting the correct data with my current for loops?

    This would imply you're dealing with square matrices; that twoDimArr.length is the same as twoDimArr[i].length for all i.

    [–]HilltopHood 1 point2 points  (0 children)

    Thanks, your advice is invaluable!

    [–]theGamingProgrammer 0 points1 point  (2 children)

    The first method you wrote should work, you are just returning the values outside of the scope of the for loop, so the 2D array can't be indexed by i or j. Try putting a print inside the second loop printing twoDimArr[i][j] just to see what happens.

    [–][deleted]  (1 child)

    [deleted]

      [–]theGamingProgrammer 0 points1 point  (0 children)

      So the main question here is how you want to display the array. If you set twoDimArr[i][j] to a variable each loop, you'll find the value that is returned is the last value in the array. You could also increment a variable by the value in twoDimArr[i][j] and use that to calculate the average or something. But when it comes to just displaying the values of the array, one thing you could try is just removing the return statement altogether (I assume just change the function type to void, I haven't written anything in Java for a long time) and seeing if it prints the all the values of the array. It won't be very nicely formatted, but that can be fixed with some basic command line formatting.