So I've been tasked with completing this program for my AP Computer Science class:
Write the code that takes an array of doubles and moves all the values greater than the average to fill the array to the left. Any values less than the average that haven't been written over should be set to 0. First calculate the average and store it in a variable named average.
Example: The array [1.0 , 1.0, 3.0 4.0 ], the average is 2.25 would be transformed to [3.0, 4.0, 0.0, 0.0]
public class Array {
public static void main(String[] args) {
double[] arr = {
1.0, 2.0, 3.0, 4.0, 5.0
};
double average;
double sum = 0.0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
average = sum / arr.length;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= average)
arr[i] = arr[i];
else if (arr[i] < average) {
arr[i] = 0.0;
arr[i] = arr[i];
for (int t = i + 1; t < arr.length; t++) {
if (arr[i] >= average)
arr[i] = arr[i];
}
}
}
for (int y = 0; y < arr.length; y++)
System.out.println(arr[y]);
}
}
and the output is:
0.0
0.0
3.0
4.0
5.0
I've been working on this for a few hours and still can't get the desired output which should be : 3.0 4.0 5.0 0.0 0.0
Anyone know what I'm doing wrong?