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

5.9k views Asked by At

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?

2

There are 2 answers

0
Dung Lemanh On BEST ANSWER
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;
    }
}
0
MBo On

For the second step make two indexes: current index i and index of the place to fill j

At every i-step: if value at current index is larger than average, copy it into j-th element and increment j

I hope that the last step with zero-filling after the last j is simple enough