gpt4 book ai didi

java - 将 Point 的值打印到终端

转载 作者:行者123 更新时间:2023-12-01 07:58:43 24 4
gpt4 key购买 nike

我创建了一个类,可以找到两点之间的距离以及它们之间的中点的值:

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 void setX(double x) {
this.x = x;
}

public double getY() {
return y;
}

public void setY(double y) {
this.y = y;
}

public static void main (String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(4,5);
System.out.println("The distance between p1 and p2 is: " + distance(p1, p2));
System.out.println("The midpoint of p1 and p2 is: " + findMidpoint(p1, p2));
}

public static double distance(Point p1, Point p2) {
return Math.sqrt((p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +
(p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}

public static Point findMidpoint (Point p1, Point p2) {
return new Point((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
}
}

这段代码编译得很好,但是当我运行它时,它给出了输出:

The distance between p1 and p2 is: 5.0
The midpoint of p1 and p2 is: Point@15db9742

无论 p1 和 p2 的值如何,它都会为中点提供相同的值。我想以“(x,y)”格式输出中点。

有人还可以解释一下为什么我被迫将距离和 findMidpoint 方法设为静态吗?

最佳答案

为什么我每次都会得到相同的输出?

因为您没有重写 toString 方法。您看到的值是 java 的 toString 实现。每个对象都有这种行为。

将此方法放入您的点类中以覆盖 java 的 toString 实现。

@Override
public String toString(){
return "("+x+", "+y+")";
}

这将为您提供您请求的 (x, y) 格式的输出。

为什么中点和距离是静态的?

静态方法是一个设计决策。它们可以写成非静态的,但意义不大,因为这些方法不会改变所涉及的任一点对象的状态。

关于java - 将 Point 的值打印到终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27095731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com