0

我对 Java 很陌生,我似乎无法弄清楚为什么我的代码不起作用。理论上,它应该打印出 (0.0) 和我插入类中的任何内容之间的距离。有人可以帮帮我吗?

public class Homework61 {
    double x;
    double y;

    Homework61(double q, double r) {
        double x = q;
        double y = r;
    }

    Homework61() {
        x = 0.0;
        y = 0.0;
    }

    public String toString() {
        String a = "(" + x + "," + y + ")";
        return a;
    }

    public double distanceFromOrigin()

    {
        double z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        return z;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Homework61 p = new Homework61();
        System.out.println(p.toString() + " Is this far from origin: "
                + p.distanceFromOrigin());
        p = new Homework61(3, 4);
        p.x = 3;
        p.y = 4;
        System.out.println(p.toString() + " Is this far from origin: "
                + p.distanceFromOrigin());
    }
}
4

2 回答 2

3
Homework61(double q, double r) {
    double x = q;
    double y = r;
}

创建 2 个局部变量 x 和 y 然后对它们不做任何事情。你大概是说

Homework61(double q, double r) {
    this.x = q;
    this.y = r;
}

另外,您只在填充对象之前打印距离(x 和 y 始终为 0)。

于 2013-04-15T02:49:08.000 回答
1
double x;
double y;

Homework61(double q, double r) {
        double x = q;
        double y = r;
    }

在上述情况下,即使您有 x 和 y 类变量,在构造函数 Homework61 中再次使用相同的名称创建 x 和 y 局部变量,其生命将在构造函数大括号的末尾退出。

如果您希望在声明的 x 和 y 类变量中初始化接收参数值,请使用this指针。

this指针用于区分局部变量和类变量,即it prevents the ambiguity between local variables and class variables

因此你必须像这样初始化它

Homework61(double q, double r) {
    this.x = q;
    this.y = r;
}
于 2013-04-15T02:58:20.720 回答