Java:替换数组中的值并移动数组中的元素

Java: Replacing the values in an array and shifting the elements in an array

所以我的任务是完成我的 AP 计算机科学课程 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]);
  }
}

输出为:

0.0
0.0
3.0
4.0
5.0

我已经为此工作了几个小时,但仍然无法获得所需的输出,应该是:3.0 4.0 5.0 0.0 0.0

有人知道我做错了什么吗?

第二步做两个索引:当前索引i和要填充的地方索引j

在每 i 步:如果当前索引处的值大于平均值,则将其复制到第 j 个元素并递增 j

希望最后一步j后的补零步骤足够简单

public class RearrangeArray {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
         double[] arr = {1.0,2.0,3.0,4.0,5.0};
         double[] newArr = new double[arr.length];

         double sum = 0.0;  
         for (int i = 0; i < arr.length; i++)
              sum += arr[i];
         double average = sum / arr.length;

         System.out.println("average = " + average);
         int n = 0;
         for(int i = 0; i < arr.length; i++)
         {
            boolean check = compare(arr[i],average);
            if(check)
            {
                newArr[n] = arr[i];
                n++;
            }
         }

         for (int i = 0; i < arr.length; i++)
         {
            System.out.print(newArr[i] + " ");
         }

    }
    public static boolean compare(double key, double average)
    {
        if(key >= average)
            return true;
        return false;
    }
}