Project Review in 2D Arrays

I can’t understand why the following is not working:

 //You have allowed the students to complete an extra credit activity to contribute towards their scores. For all exam grades less than 90, add 2 additional points to the grade in 
            for (double[] row : newScores){
                for ( double grade : row){
                    if ( grade < 90){
                        grade += 2;

It’s not working or it’s throwing errors?

Have you tried println statements within the loop to see what is happening inside?

The matrix is printed out unchanged.

Have you tried println statements inside the loop to see whether the code you wrote is acting as you envisioned?

I just did. Thank you for insisting on println statements inside the loop. So, if I’m getting this right, enhanced “for” loops make it easy to traverse over an array, but they are not helpful if you need to change the values within the array.

I think array traversal is always dependent on context. Sometimes, you use a hashmap or another array to store your changes, sometimes you make changes in place. Other times you might even use recursion. And yet other times you use pointers to achieve your desired effect (the possibilities are many!).

For sure, if you want to make changes to the array proper as you iterate, it’s usually good to avoid changes that change it’s length (without making a copy). Sometimes it’s doable but often case there’s a simpler way.

1 Like