再设计一个主类,放在自定义的包里,从键盘输入2个点的坐标,通过导入自定义的包,得到两点之间的距离
时间: 2024-05-02 19:16:26 浏览: 13
首先,我们需要创建一个新的包,可以命名为`com.example.geometry`,然后在该包下创建一个名为`Point`的类,用于表示一个点,代码如下:
```java
package com.example.geometry;
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
```
接下来,我们可以在该包下再创建一个类`DistanceCalculator`,用于计算两个点之间的距离,代码如下:
```java
package com.example.geometry;
public class DistanceCalculator {
public static double calculate(Point p1, Point p2) {
double xDiff = p1.getX() - p2.getX();
double yDiff = p1.getY() - p2.getY();
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
```
最后,在`main`函数中,我们可以通过键盘输入获取两个点的坐标,并计算它们之间的距离,代码如下:
```java
import com.example.geometry.DistanceCalculator;
import com.example.geometry.Point;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the coordinates of point 1 (x y): ");
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();
Point p1 = new Point(x1, y1);
System.out.print("Enter the coordinates of point 2 (x y): ");
double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
Point p2 = new Point(x2, y2);
double distance = DistanceCalculator.calculate(p1, p2);
System.out.println("The distance between the two points is: " + distance);
}
}
```
这样,我们就可以通过导入自定义的包,实现计算两个点之间距离的功能了。