Issue
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);
}
}
Solution
In addition to Rafael's answer, be careful with braces and where you'd like to system out.
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[zx];
}
System.out.println(val);
}
Above code will increment val with each value inside the array and sum inside val variable. Print is done afterwards.
There were some issues with your array initialization and use of arrays and indexes. I suggest you read a bit more on this because this is important on programming
Finally, a better name for the index variable would be i or index instead of zx.
Answered By - Daniel Vilas-Boas
Answer Checked By - Candace Johnson (JavaFixing Volunteer)