gpt4 book ai didi

java - 找到数组中最接近的值并将其删除

转载 作者:行者123 更新时间:2023-12-01 20:07:54 26 4
gpt4 key购买 nike

我已经搜索了几个具有确切问题的类似线程,但是我无法使代码正常工作,我想找到数组中最接近的值然后将其删除,这是我的代码:

import java.util.ArrayList;
import java.util.Scanner;
public class Entertrain {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;

while (console.hasNextInt()) {
weight.add(console.nextInt());

}

for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);

if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon

}
System.out.println(averageWagon);

System.out.println(weight);
System.out.println(power);
System.out.println(sum);

}
}

如果可以指导我找到解决方案,我已经尝试了几个小时,最后得出的结论是我严重缺乏数组知识,所以无论如何我都会把它放在一边现在重点关注数组,但如果您在这方面获得帮助,我将不胜感激。

最佳答案

你要找的不是数组,而是集合。您正在使用 ArrayList,它实现了 List。

public static void main(String[] args) {

Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;

while (console.hasNextInt()) {
weight.add(console.nextInt());
}

for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);

if (sum > power) {
averageWagon = sum / weight.size();

Integer closest = weight.get(0);
for (Integer i: weight) {
if (Math.abs(averageWagon - closest) > Math.abs(averageWagon - i))
closest = i;
}
weight.remove(closest);
}
System.out.println(averageWagon);

System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}

关于java - 找到数组中最接近的值并将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com