简体   繁体   English

查找arrayList中位数的问题

[英]Problems finding median of arrayList

I keep getting The type of the expression must be an array type but it resolved to ArrayList<Double> The arrayList is pulling numbers from my Test class.我不断得到The type of the expression must be an array type but it resolved to ArrayList<Double> arrayList 正在从我的测试类中提取数字。 I made the if to determine if the arrayList has an even amount of values in it or an odd, for I could use the two different ways to determine the median.我使用 if 来确定 arrayList 中的值是偶数还是奇数,因为我可以使用两种不同的方法来确定中位数。 But I'm not able to get the median formula to work.但是我无法使中位数公式起作用。

public class Data {

private ArrayList<Double> sets;

public Data(double[] set) {
    this.sets = new ArrayList<Double>();
    for (double i : set) {
        this.sets.add(i);
    }
}

public double getMedian(){
    Collections.sort(sets);

    double middle = sets.size()/2;
        if (sets.size()%2 == 1) {
           middle = (sets[sets.size()/2] + sets[sets.size()/2 - 1])/2;
        } else {
            middle = sets[sets.size() / 2];
        }
      return middle;
}

The problem is on the line where you find the middle:问题出在你找到中间的那一行:

middle = (sets[sets.size()/2] + sets[sets.size()/2 - 1])/2;

You can use [index] notation only with arrays.您只能对数组使用 [index] 表示法。 You need to use getter/setter methods to access the elements of an ArrayList.您需要使用 getter/setter 方法来访问 ArrayList 的元素。 This should work:这应该有效:

middle = (sets.get(sets.size()/2) + sets.get(sets.size()/2 - 1))/2;

You are using arrayList not an array, so ArrayList's get(int index) method must be used to access data.您使用的arrayList不是数组,因此必须使用 ArrayList 的get(int index)方法来访问数据。 This is used like this :这是这样使用的:

middle = (sets.get(sets.size()/2) +sets.get((sets.size()/2)-1) )/2;

The problem is that, if you have an array with 4 elements [0..3], to find the median you just do 4/2 - 1 = 1 and index 1 is the median of array.问题是,如果您有一个包含 4 个元素 [0..3] 的数组,要找到中位数,您只需执行 4/2 - 1 = 1 并且索引 1 是数组的中位数。 Now if array is 5, you just do 5/2 = 2 and 2 is the median.现在如果数组是 5,你只需做 5/2 = 2 并且 2 是中位数。

public double getMedian() {
    Collections.sort(sets);
    int middle = sets.size() / 2;
    middle = middle > 0 && middle % 2 == 0 ? middle - 1 : middle;
    return sets.get(middle);
}

Make sure in your if statement you check if it's equal to 0.确保在 if 语句中检查它是否等于 0。

public double getMedian(){
    Collections.sort(sets);

    double middle = sets.size()/2;
        if (sets.size()%2 == 0) {
           middle = (sets.get(sets.size()/2) + sets.get(sets.size()/2 - 1))/2;
        } else {
            middle = sets[sets.size() / 2];
        }
      return middle;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM