gpt4 book ai didi

java - 基于对象类重写java中的打印语句

转载 作者:行者123 更新时间:2023-12-02 09:12:52 26 4
gpt4 key购买 nike

我有以下 Java 代码

我可以在 printDistance 方法中打印计算值。

输出:

4.0

3.0

但我需要以下格式的输出(预期输出)。请帮忙

3D 距离 = 4.0

二维距离 = 3.0

 public class Point2D {

double x;
double y;

public double getX() {
return x;
}

public double getY() {
return y;
}

public Point2D(double x, double y) {
this.x = x;
this.y = y;
}

public double dist2D(Point2D p) {
x = (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2)));
return x;
}

public static void printDistance(double d) {
System.out.println(d);
}

static public void main(String args[]) {
Point3D obj1 = new Point3D(1.0, 2.0, 3.0);
Point3D obj2 = new Point3D(3.0, 4.0,5.0);
printDistance(obj1.dist3D(obj2));
printDistance(obj1.dist2D(obj2));
}
}

class Point3D extends Point2D {

double z;

public double getZ() {
return z;
}

public Point3D(double x, double y, double z) {
super(x, y);
this.z = z;
}

public double dist3D(Point3D p) {
return (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2) + +Math.pow((p.getZ() - z), 2)));
}
}

最佳答案

您可以按如下方式进行:

public class Point2D {

double x;
double y;

public double getX() {
return x;
}

public double getY() {
return y;
}

public Point2D(double x, double y) {
this.x = x;
this.y = y;
}

public String dist2D(Point2D p) {
x = (int) Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2)));
return "2D Distance = "+x;
}

public static void printDistance(String d) {
System.out.println(d);
}

static public void main(String args[]) {
Point3D obj1 = new Point3D(1.0, 2.0, 3.0);
Point3D obj2 = new Point3D(3.0, 4.0,5.0);
printDistance(obj1.dist3D(obj2));
printDistance(obj1.dist2D(obj2));
}
}

class Point3D extends Point2D {

double z;

public double getZ() {
return z;
}

public Point3D(double x, double y, double z) {
super(x, y);
this.z = z;
}

public String dist3D(Point3D p) {
return "3D Distance = "+ Math.ceil(Math.sqrt(Math.pow((p.getX() - x), 2) + Math.pow((p.getY() - y), 2) + +Math.pow((p.getZ() - z), 2)));
}
}

输出:

3D Distance = 4.0
2D Distance = 3.0

关于java - 基于对象类重写java中的打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257244/

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