为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用另一个类中的对象的特定变量?

如何使用另一个类中的对象的特定变量?

慕莱坞森 2022-05-25 10:04:28
我正在尝试修改 toString 方法。我有一个名为“p”的对象,它有 2 个属性作为属性,在这种情况下,5.0 和 6.0 分别是“x”和“y”值。字符串转换器“< Point >”内的括号应该打印 p 的“x”,p 的“y”,而在圆圈中它应该打印半径。果然打印半径有效,但我不确定我应该如何指定p的“x”和p的“y”。班级圈:package packageName;public class Circle {public Point center;public double radius;public Circle(Point a, double b) {    this.center = a;    this.radius = b;}    public String toString() {        String converter = "<Circle(<Point(" + (x of p) + ", " + (y of p) + ")>, " + this.radius + ")>";        return converter;    }    public static void main(String args []) {        Point p = new Point(5.0, 6.0);        Circle c = new Circle(p, 4.0);        c.toString();    }}  上课点:package packageName;public class Point{public double x;public double y;public Point(double x, double y) {    this.x = x;    this.y = y;}public String toString() {    String input = "<Point(" + this.x + ", " + this.y + ")>";    return input;  }}
查看完整描述

3 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

您是说您想在 的方法中打印“p”的“x”和“p”的“y” toString,Cirlce但toString不知道任何事情,p因为p在方法中本地声明main。


在该main方法中,您创建p并将其传递给 的第一个参数Circle,然后将其分配给center。所以center存储与p. 你应该使用center.xand center.y:


String converter = "<Circle(<Point(" + center,x + ", " + center.y + ")>, " + this.radius + ")>";

return converter;

或者,您可以center.toString()直接致电:


String converter = "<Circle(" + c.toString() + ", " + this.radius + ")>";

return converter;

请注意我是如何使用语法foo.bar来表示“foo 的 bar”的。这是点符号,您似乎对此不熟悉。


查看完整回答
反对 回复 2022-05-25
?
UYOU

TA贡献1878条经验 获得超4个赞

pmain方法的局部变量,因此变量p本身不能在您要使用的地方使用。

但我有个好消息——您将Point实例作为参数传递给Circle构造函数,并将其存储在center字段中。

您可以将其引用为this.center或只是center. 要引用x指定的Point实例,请使用

this.center.x


查看完整回答
反对 回复 2022-05-25
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您可以使用 center.x 和 center.y,如下所示:


String converter = "<Circle(<Point(" + this.center.x + ", " + this.center.y + ")>, " + this.radius + ")>";

或者您只需将 Point 类的 x 和 y 变量设为私有并使用 getter 方法,如下所示:


private double x;

private double y;


public double getX(){

    return this.x;

}

public double getY(){

    return this.y;

}

并使用


String converter = "<Circle(<Point(" + this.center.getX() + ", " + this.center.getY() + ")>, " + this.radius + ")>"; 



查看完整回答
反对 回复 2022-05-25
  • 3 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信