I can't figure out why my outcome is not:
Your first array element is: 0
1
2
3
4
5
6
(the expected output)
My code:
public class day7 {
public static void main(String[] args){
int arrayZ[] = new int[7];
arrayZ[0] = 0;
System.out.println("Your first array element is: " + arrayZ[0]);
int i = 1;
while (i <= 6){
arrayZ[i] = i;
i++;
System.out.println(arrayZ[i]);
}
System.out.println("Each entry of the array is: " + arrayZ[0] + " " + arrayZ[1] + " " + arrayZ[2] + " " + arrayZ[3] + " " + arrayZ[4] + " " + arrayZ[5] + " " + arrayZ[6]);
System.out.println("And, the sum of all array elements are: " + arrayZ[0] + arrayZ[1] + arrayZ[2] + arrayZ[3] + arrayZ[4] + arrayZ[5] + arrayZ[6]);
}
}
Outcome/actual output:
Your first array element is: 0
0
0
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at day7.main(day7.java:14)
whilelooping which relies on an inc/decrement sentinel value (i.e.;iin your case) a for loop is generally the more concise option.for (int i = 0; i <= 6; ++i) { ... }.