定义一个点类 Point,类中包括构造方法, 以及求两点之间最短距离的方法。编写测试类 , 测试 Point编写是否正确
时间: 2024-10-13 07:05:50 浏览: 72
首先,我们可以创建一个名为`Point`的类,它包含两个属性(通常是坐标x和y),一个构造函数用于初始化这两个属性,以及一个计算两点间距离的方法。这里是一个简单的Java实现:
```java
public class Point {
private double x;
private double y;
// 构造方法
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// 计算两点之间的欧几里得距离
public double distanceTo(Point other) {
double deltaX = this.x - other.x;
double deltaY = this.y - other.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
}
```
接下来,我们编写一个测试类`PointTest`来验证`Point`类的功能:
```java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PointTest {
@Test
public void testDistance() {
// 创建两个点实例
Point pointA = new Point(0, 0);
Point pointB = new Point(3, 4);
// 计算并预期结果
double expectedDistance = Math.sqrt(3^2 + 4^2); // 求5的距离
// 调用distanceTo方法并检查结果
assertEquals(expectedDistance, pointA.distanceTo(pointB), 0.0001);
}
}
```
在这个测试类中,我们创建了两个点(例如原点和(3, 4)点),然后通过`distanceTo`方法计算它们之间的距离,并使用断言保证得到的结果与预期一致。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)