我需要弄清楚如何删除数组列表中的最小数字。用户将输入他们想要删除的数量。这就是我到目前为止所拥有的。 (这个程序将给出一个数组列表的加权平均值,但我仍然坚持这一部分。)
公共类WeightedAvgDropSmallest {
public static ArrayList numbers() {
ArrayList<Double> nums = new ArrayList<Double>();
Scanner in = new Scanner(System.in);
System.out.println("Enter 5-10 numbers to be weighted averaged. Type Z to quit: ");
while (in.hasNextDouble()) {
nums.add(in.nextDouble());
}
return nums;
}
public static int droper() {
Scanner in = new Scanner(System.in);
System.out.println("Enter how many numbers do you want to drop: ");
int drop = in.nextInt();
return drop;
}
public static double weight() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the weight: ");
double weight = in.nextDouble();
return weight;
}
public static double averager(ArrayList<Double> nums, int drop, double weight) {
double average = 0;
double min = nums.get(0);
int counter = 0;
while (counter <= drop) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i) < min) {
min = nums.get(i);
}
}
counter++;
}
return average;
}
public static void main(String[] args) {
ArrayList<Double> nums = numbers();
int droper = droper();
double weight = weight();
averager(nums, droper, weight);
}
}
答案 0 :(得分:0)
您应该在删除元素之前对列表进行排序。使用:
Arrays.sort(nums.toArray());
然后使用:
删除n个第一个元素for(i=0; i<n; i++)
nums.remove(i);
另一种可能性是在插入新数字时通过二进制搜索使列表首先排序(我假设它们没有排序)。这个选项需要你编写更多的代码,我认为就计算复杂性而言,它们是公平的。