Java 求一个子串中的两个中位数

Java find two median in a substring

这里是 java 的新手,我有一个新手问题。

我最近收到了这个 txt 文件:

Albuquerque, New Mexico, 5352 feet, 202.3°
Denver, Colorado, 5280 feet, 202.4°
Minneapolis, Minnesota, 841 feet, 210.5°
Birmingham, Alabama, 644 feet, 210.8°
Detroit, Michigan, 639 feet, 210.8°
Miami, Florida, 11 feet, 211.9°
Burj Khalifa, Dubai, 2717 feet, 207.1°
CN Tower, Toronto, 1815 feet, 208.7°

并被要求找出并打印出这两个中位数。问题是我在尝试使用 Arrays.sort() 时不断出错。

public static void main(String[] args) {
    File mf = new File("C:\file.txt");
    ArrayList<String> inData = new ArrayList<String>();
    String strline;

    try {
        FileInputStream fstream = new FileInputStream(mf);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        while ((strline = br.readLine()) != null) {
            strline = strline.trim();
            if ((strline.length() != 0)) {
                inData.add(strline);
            }
        }
        br.close();
    } catch (Exception e) {
        System.err.println("Error CANNOT FIND FILE!");
    }

    //Calc median start
    double median;
    for (int i = 0; i < inData.size(); i++) {
        String[] word = inData.get(i).split(", ");
        double m = Double.parseDouble(word[3].substring(0, 5));
        Arrays.sort(m);
        if (m.length % 2 == 0) {
            double middleNumOne = m[m.length / 2 - 0.5]
            double middleNumTwo = m[m.length / 2 + 0.5]
            System.out.println("Median:" + middleNumOne + "and" + middleNumTwo);
        }
    }
}

这就是我目前所拥有的。有人可以帮助我,告诉我我错过了什么吗?

你不能使用 Arrays.sort(m);m var 是一个 double 我想你的意思是 Array.sort(word) 等等代码的其余部分......

如果需要创建double数组来计算中位数,check this question

只是为您说明,这是您需要更改的内容:

double[] median = new double[inData.size()];

for (int i=0; i < inData.size(); i++) {
    String[] word = inData.get(i).split(", "); 
    double m = Double.parseDouble(word[3].substring (0,5));
    median[i] = m;
}

Arrays.sort(median);

然后代码中此点之后对 m 的所有引用都应更改为 median

    List<Double> altitudes = new ArrayList<Double>();
    for (int i = 0; i < inData.size(); i++) {
        String[] word = inData.get(i).split(", ");
        double m = Double.parseDouble(word[3].substring(0, 5));
        altitudes.add(m);
    }
    Double[] array = altitudes.toArray(new Double[] {});
    Arrays.sort(array);
    for (Double double1 : array) {
        System.out.println(" " + double1);
    }
    if (array.length % 2 == 0) {

        double middleNumOne = array[(int) (array.length / 2 - 0.5)];
        double middleNumTwo = array[(int) (array.length / 2 + 0.5)];

        System.out.println("Median: " + middleNumOne + " and " + middleNumTwo);
    }