你如何找到阵列的中位数?

时间:2015-04-21 15:05:50

标签: java arrays sorting median

我找到了一个有类似问题的人(How to calculate the median of an array?),但我无法弄清楚如何将其纳入我自己的代码,因为我对java很新。现在,我的findmedian方法返回0而不是实际中位数,我似乎无法弄明白。谢谢!

import java.util.Scanner;
import java.util.Arrays;

public class Original
{
    public static void main(String[] args)
    {
        Scanner inputNumber = new Scanner(System.in);
        Scanner dataItem = new Scanner(System.in);
        Scanner input = new Scanner(System.in);

        System.out.print("This stores a list of contirbutions to a charity drive.\n ");
        System.out.print("How many contributors will be entered? ");

        double contributors = inputNumber.nextDouble();
        double contributions[ ] = new double[50];  
        double contributions_check[] = findData (contributors, contributions);

        System.out.print("See if the contributions are correct. ");

        // Displays the contributions, loop allows numbers to be displayed correctly
        for (int count = 0; count < contributors; count++) {
            System.out.print(contributions_check[count] + "    ");
        }

        double median = findmedian(contributors,contributions_check);
        System.out.print("\n The median contribution is: " + median);
    }

    public static double[] findData(double n, double[] contributions2)
    {
        Scanner dataItem = new Scanner(System.in);

        // x must be 0 and x must be < than n
        for (int x = 0; x < n; x++) {
            System.out.print("Please enter the next contribution: ");
            contributions2[x] = dataItem.nextDouble();
        }

        return contributions2;
    }

    public static double findmedian(double n, double data[])
    {
        Arrays.sort(data);
        double median;

        if (data.length % 2 == 0) {
            median = ((double) data[data.length / 2] +
                      (double) data[data.length / 2 - 1]) / 2;
        } else {
            median = (double) data[data.length/2];
        }

        return median;
    }
}

2 个答案:

答案 0 :(得分:2)

我认为问题是您在data.length中使用findmedian,您应该使用ndata.length始终为50,即使您只输入了5个项目....

答案 1 :(得分:0)

使用贡献者数量n来了解数组中的有效贡献者。

  public static double findmedian(double n, double data[])
        {
            Arrays.sort(data);
            double median;

            if (data.length % 2 == 0) {
                median = ((double) data[n / 2] +
                          (double) data[n / 2 - 1]) / 2;
            } else {
                median = (double) data[n/2];
            }

            return median;
        }