Java1.设计一个Point类表示平面坐标系中的点。该类包括私有的double型的x和y属性。两个构造方法,一个是无参的构造方法,该方法中x和y的值为0;另外一个构造方法包含两个参数,分别为x和y赋值。为x和y属性提供setter和getter方法,重写Object类的hashcode和equals方法。最后重写Object类的toString()方法。编写一个类,包含如下功能:(1)定义一个数组,数组的长度是50,数组元素是Point的对象。Point对象的x和y值随机赋值。(2)判断数组中是否有两个相等的点(点的x和y的值相等)(3)指定一个点,求该点到其他点的距离(两种理解)(4)求距离最近的两个点。
时间: 2023-05-27 11:06:49 浏览: 172
Point类的实现:
```java
import java.util.Objects;
public class Point {
private double x;
private double y;
public Point() {
this.x = 0;
this.y = 0;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Point point = (Point) obj;
return Double.compare(point.x, x) == 0 && Double.compare(point.y, y) == 0;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
```
使用Point类的类的实现:
```java
import java.util.Arrays;
import java.util.Random;
public class PointTest {
public static void main(String[] args) {
Point[] points = new Point[50];
Random random = new Random();
for (int i = 0; i < points.length; i++) {
double x = random.nextDouble() * 100;
double y = random.nextDouble() * 100;
points[i] = new Point(x, y);
}
// 判断数组中是否有两个相等的点
boolean hasEqualPoints = false;
for (int i = 0; i < points.length - 1; i++) {
for (int j = i + 1; j < points.length; j++) {
if (points[i].equals(points[j])) {
hasEqualPoints = true;
System.out.println("数组中有两个相等的点:" + points[i] + "," + points[j]);
break;
}
}
if (hasEqualPoints) {
break;
}
}
if (!hasEqualPoints) {
System.out.println("数组中没有两个相等的点。");
}
// 指定一个点,求该点到其他点的距离
Point p = new Point(50, 50);
System.out.println("点" + p + "到其他点的距离:");
for (Point point : points) {
double distance = getDistance(p, point);
System.out.println(" " + point + ":" + distance);
}
// 求距离最近的两个点
double minDistance = Double.MAX_VALUE;
Point minPoint1 = null;
Point minPoint2 = null;
for (int i = 0; i < points.length - 1; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = getDistance(points[i], points[j]);
if (distance < minDistance) {
minDistance = distance;
minPoint1 = points[i];
minPoint2 = points[j];
}
}
}
System.out.println("距离最近的两个点:" + minPoint1 + "," + minPoint2);
}
/**
* 计算两个点之间的距离
*
* @param p1 点1
* @param p2 点2
* @return 距离
*/
private static double getDistance(Point p1, Point p2) {
double dx = p1.getX() - p2.getX();
double dy = p1.getY() - p2.getY();
return Math.sqrt(dx * dx + dy * dy);
}
}
```
阅读全文