查找arrayList中位数的问题 [英] Problems finding median of arrayList
问题描述
我不断收到 表达式的类型必须是数组类型,但它解析为 ArrayList
arrayList 正在从我的测试类中提取数字.我使用 if 来确定 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. 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. 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;
您只能对数组使用 [index] 表示法.您需要使用 getter/setter 方法来访问 ArrayList 的元素.这应该有效:
You can use [index] notation only with arrays. You need to use getter/setter methods to access the elements of an ArrayList. This should work:
middle = (sets.get(sets.size()/2) + sets.get(sets.size()/2 - 1))/2;
这篇关于查找arrayList中位数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!