java - 使用构造函数计算两点之间的欧几里得距离
问题描述
我正在编写一个 Java 程序,该程序使用以下构造函数实现 Point 数据类型:
点(双 x,双 y,双 z)
以及以下 API:
double distanceto(Point q) 它返回 this 和 q 之间的欧几里得距离。(x1, y1, z1) 和 (x2, y2, z2) 之间的欧几里得距离定义为 sqrt( (x1-x2)^2 + (y1-y2)^2) + (z1-z2)^2)。
String toString() – 它返回点的字符串表示形式。一个例子是 (2.3,4.5,3.0)。
在用于测试它的类中编写一个 main 方法。它应该使用用户在命令行上提供的输入创建两个 Point 对象。然后它应该打印出两个点,然后是它们的欧几里德距离。样本运行如下。
java点2.1 3.0 3.5 4 5.2 3.5
第一点是(2.1,3.0,3.5)
第二点是(4.0,5.2,3.5)
他们的欧几里得距离是 2.90
该程序无法编译,但我不知道为什么。我是编程新手,所以我按照在线和 Codecademy 的一些步骤尝试访问构造函数中的对象,但我认为我做错了。任何建议将不胜感激。
public class Point {
double x1;
double y1;
double z1;
double x2;
double y2;
double z2;
public Point(double x, double y, double z){
x1 = x;
y1 = y;
z1 = z;
x2 = x;
y2 = y;
z2 = z;
}
public double distanceTo(Point q){
return Math.sqrt(Math.pow((x1-x2), 2.0) + Math.pow((y1-y2), 2.0) + Math.pow((z1-z2), 2.0));
}
double x3 = x1-x2;
double y3 = y1-y2;
double z3 = z1-z2;
public String toString() {
return "(" + x3 + ", " + y3 + ", " + z3 + ")";
}
public static void main (String[]args){
Point pointOne = new Point(args[0]);
Point pointTwo = new Point(args[1]);
Point distance = new distanceTo();
System.out.println("The first point is " + "(" + pointOne + ")");
System.out.println("The second point is " + "(" + pointTwo + ")");
System.out.println("Their Euclidean distance is " + distance);
}
}
解决方案
有几件事:
首先,您的 Point 类应该只需要一组变量。只需制作一组并构造两个点对象。
在 distanceTo() 方法中,通过执行 q.x1、q.y1 等来访问其他点的坐标。
在 main 方法中,距离应该是 pointOne 到 pointTwo 的距离的两倍。这是对我有用的代码
class Point {
double x1;
double y1;
double z1;
public Point(double x, double y, double z){
//each point object only needs one x, y and z
x1 = x;
y1 = y;
z1 = z;
}
public double distanceTo(Point pointTwo){
return Math.sqrt(Math.pow(pointTwo.x1-x1, 2.0) + Math.pow(pointTwo.y1-y1, 2.0) + Math.pow(pointTwo.z1-z1, 2.0));
//formula is sqrt((p2.x-p1)^2 + (p2.y-p1.y)^2 + (p2.z - p1.z)^2
}
public String toString() {
return "(" + x1 + ", " + y1 + ", " + z1 + ")";
//we don't need a diff set of variables here
}
public static void main (String[]args){
//make two diff points with coords
Point pointOne = new Point(2.1, 3.0, 3.5);
Point pointTwo = new Point(4.0,5.2, 3.5);
double distance = pointOne.distanceTo(pointTwo);
//uses point two as the parameter (x2, y2, z2 in formula)
System.out.println("The first point is " + "(" + pointOne + ")");
System.out.println("The second point is " + "(" + pointTwo + ")");
System.out.println("Their Euclidean distance is " + distance);
}
}
推荐阅读
- python - python将字典复制到excel中
- python - Python程序中加密的识别
- string - 如何从字符串中删除标记并将其变成列表
- azure - 在 VSTS Azure Powershell 任务中使用 Set-AzureStorageBlobContent 时出现“无法获取存储上下文”错误
- android - Android传感器如何随时获取精度?
- php - 如何制作这种htaccess
- php - phroute 无法正常工作,说路由未定义
- swift - RXSwift 如何结合最新使用,长什么样,闭包中的匿名类并处理附加参数
- mysql - MySQL 仅按日期搜索时间戳列
- ajax - POST 请求适用于 AJAX,但不适用于 fetch