Home > Back-end >  How do I debug arrays?
How do I debug arrays?

Time:05-05

I have this assignment that I am having trouble on. I'm supposed to fix syntax error in the code to produce the desired number. I fixed the amount of arrays from 4 to 3 and added "[]" to the end of array in the for loop. I don't know what else there is to fix. Can anyone help?

//
// Fix the compiler errors.  The program should display the value 6.
//
package debug5;

public class debug5 {

    public static void rain(String[] args) {}
        int val = 0;  // initialize val to 0.
        int array[] = new int[3];  // create an array of 3 integers.
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;

        // add up the values in the array.
        for (int zx = 0;zx < array.length;zx  )
        }
            val  = array;
        {

        system.out.println(val);
    }

}

My version :

//
// Fix the compiler errors.  The program should display the value 6.
//

package debug5;

public class debug5 {

    public static void rain(String[] args) {}
        int val = 0;  // initialize val to 0.
        int array[] = new int[3];  // create an array of 3 integers.
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;

        // add up the values in the array.
        for (int zx = 0;zx < array.length;zx  )
        }
            val  = array[];
        {
        
        system.out.println(val);
    }

}

CodePudding user response:

Try this:

val  = array[zx];

You have to use the index of the array.

CodePudding user response:

In addition to Rafael's answer, be careful with braces and where you'd like to system out.

for (int zx = 0;zx < array.length;zx  ){
        val  = array[zx];
        system.out.println(val);
        }
    }

Above code will increment val with each value inside the array and print each time the loop is run. If you just want the sum, keep system out outside the loop.

A better name for the index variable would be i or index instead of zx.

  • Related