谁能帮我弄清楚如何进行这个计算?我一直在兜圈子,老实说我不知道该怎么办。这是我当前正在处理的文件:
import java.util.*;
import java.io.*;
public class Assignment_12 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("name goes here");
System.out.println("You may quit at any time by typing \"Q\".");
ArrayList<Double> numbers = new ArrayList<Double>();
ArrayList<Double> numbers2 = new ArrayList<Double>();
System.out.println("Please enter an X coordinate: ");
//Point pnt = new Point();
while (input.hasNextDouble()) {
numbers.add(input.nextDouble());
System.out.println("Please enter a Y coordinate: ");
numbers2.add(input.nextDouble());
double x = (double) numbers.get(0);
double y = (double) numbers2.get(0);
Point pnt = new Point(x, y);
System.out.println(pnt.getX()); // just to make sure the "object created"?
System.out.println(pnt.getY()); // same as before, I think
System.out.println(pnt.distance(pnt.getX(), pnt.getY())); // how to calculate??
}
if (input.equals("Q")){
System.exit(0);
}
}
}
这就是我只是想弄清楚如何进行实际计算的类:
public class Point {
private double x;
private double y;
public Point(){
this.x = 0.0;
this.y = 0.0;
}
public Point(double x,double y){
this.x = x;
this.y = y;
}
public double distance(Point pt){
return Math.sqrt((x - pt.x)*(x - pt.x) + (y - pt.y)*(y - pt.y));
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
我真的很苦恼到底该做什么。我似乎用 x
和 y
创建了 pnt
对象,但我不一定了解如何使计算出的距离可用于打印。我尝试过 System.out.println(pnt.distance(pnt.getX(), pnt.getY())); 和其他类似的东西,但我只是被难住了。任何建议将不胜感激!
最佳答案
仔细查看方法的签名:
double distance(Point pt)
// ⬑ single parameter of type Point
此方法是在 Point
上调用的,您可以使用 point.distance(...
) 正确执行此操作。但它需要 一个 参数,它也是 Point
类型。不过,您没有传递 Point
。让我稍微改一下您的代码:
double someX = pnt.getX();
double someY = pnt.getY();
pnt.distance(someX, someY)
这是行不通的,因为您传递的是两个double
,而不是一个Point
。所以你可以做的是:
pnt.distance(pnt)
// ⬑ single parameter of type Point
将其与您所做的进行比较:
pnt.distance(pnt.getX(), pnt.getY())
// ⬑ ⬑ two parameters of type double
但让我指出,这将返回 0
,因为您刚刚计算了 Point
到自身的距离。尝试:
Point otherPnt = new Point(13, 8.5);
System.out.println(pnt.distance(otherPnt));
这至少会返回一个更有趣的结果。
关于java - ArrayList x,y坐标距离计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49847419/