Here is the corrected code for the U6_L5_Activity_Three class:
public class U6_L5_Activity_Three {
public static double avg(int[] arr) {
int s = 0;
for (int n : arr) {
s += n;
}
return (double) s / arr.length;
}
}
Step-by-step explanation:
The enhanced for loop should use int data type for the variable n, as the array is of type int[].
The value of s should be incremented by the value of n in each iteration of the for loop.
The division of s by the length of the array should be done after the loop is completed, not inside it.
To get a decimal average, we need to cast s to double before dividing it by the length of the array.
We can use the following runner class to test the avg method:
public class Runner {
public static void main(String[] args) {
int[] arr1 = {5, 10, 15, 20};
System.out.println(U6_L5_Activity_Three.avg(arr1)); // expected output: 12.5
int[] arr2 = {-2, 0, 2};
System.out.println(U6_L5_Activity_Three.avg(arr2)); // expected output: 0.0
int[] arr3 = {3, 7, 11};
System.out.println(U6_L5_Activity_Three.avg(arr3)); // expected output: 7.0
}
}