【发布时间】:2018-09-27 22:40:52
【问题描述】:
目标是编写代码来确定最接近 (24,5) 的 x,y 坐标。使用带有 2 个实例变量的公共类 PointXY。然后是类之外的一个公共方法,它返回最接近 (24,5) 的点。我知道我做的不对,因为 PointXY 类型的 ArrayList 让我感到困惑。提前感谢您的帮助。
public class PointXY {
private int x;
private int y;
}
public PointXY closest_24_5(ArrayList<PointXY> b) {
ArrayList<PointXY> nums = new ArrayList<PointXY>();
nums.add(new PointXY(3,6));
int total = Integer.MAX_VALUE;
for(int i=0; i<nums.size();i++) {
int dx = 24 - this.x;
int dy = 5 - this.y;
int thisDistance = Math.sqrt(dx*dx + dy*dy);
if(thisDistance<total) {
total=thisDistance;
}
}
return total;
}
【问题讨论】:
-
如果你只是想找到一堆距离中的最小值,你不需要调用
Math.sqrt。但是,如果您忽略我的建议并存储实际距离(而不是距离平方),我不建议将其存储在int中 - 通常不是。 -
我认为你应该只是遍历传递给方法的列表,寻找最近的点。无需在方法内部构造自己的
ArrayList<PointXY>。 -
好的,你有一个变量来存储你到目前为止找到的最短距离,但是你需要第二个变量来存储你到目前为止找到的最近点。这是因为您的方法实际上需要返回点,只需要返回距离。
-
我将如何浏览列表?问的问题让我很困惑。它是一个数组列表的数组列表。一个例子是 {[1,3],[2,4],[63,3]}。当做一个for循环来检查这个时,我将如何区分x和y?使用拆分?
-
原来的任务是:
标签: java class arraylist methods