0

我已经为复数编写了 complex.java 代码。但是它在eclipse上给出了错误“局部变量real可能没有被初始化”。无法弄清楚出了什么问题。代码如下。任何帮助,将不胜感激。

import java.lang.Math; 

public class Complex { 
    public double real; 
    public double comp; 

    Complex(double real, double comp) {  
    this.real = real; 
    this.comp = comp; 
    }

    Complex() { 
    this.real = 0; 
    this.comp = 0;
    }


    public double getReal() {
        return real;
    }

    public double getImg() {
        return comp;
    }


    public Complex add(Complex a) { 
        return new Complex(a.getReal() + this.real, a.getImg() + this.comp);
    }


    public static Complex add(Complex a, Complex b) { 
        double real = a.real + b.real;
        double comp = a.comp + b.comp;
        Complex sum = new Complex(real, comp);
        return sum;
    }

    public double getABS() { 
        return Math.sqrt(real*real + comp*comp);
    }

    public double getABSSqr() { /* get the squre of absolute */
        return (real*real + comp*comp);
    }


    public Complex mul(Complex a) { 
        return new Complex(a.getReal()*this.real-a.getImg()*this.comp, a.getReal()*this.comp+this.real*a.getImg());
    }

    public static Complex mul(Complex a, Complex b) { 
        double real = a.real*b.real-a.comp*b.comp;
        double comp = a.real*b.comp+b.real*a.comp;
        Complex mul = new Complex(real, comp);
        return mul;
    }

    public Complex squre() { 
        double real = real*real-comp*comp; //THIS IS WHERE ERROR APPEARS FOR real*real
        double comp = 2*real*comp;  //THIS IS WHERE ERROR APPEARS FOR comp                  
        Complex squre = new Complex(real, comp);
        return squre;
    }   

    public void display() { 
    System.out.println(this.real + " + " + this.comp + "j");
    }
}
4

3 回答 3

2

您需要在 RHS 上使用this.realthis.comp语句。那是因为您在该范围内有同名的局部变量。要将它们与实例变量区分开来,您需要使用this.

double real = this.real*this.real-this.comp*this.comp;
double comp = 2*real*this.comp; // this.comp refers the instance variable comp and real refers the real declared in the previous line

因此,如果您只给real,它将尝试使用real左侧本身的 ,它尚未初始化,因此会出现错误。

于 2013-10-01T17:28:19.500 回答
0
    double real = real*real-comp*comp; //THIS IS WHERE ERROR APPEARS FOR real*real
    double comp = 2*real*comp;  //THIS IS WHERE ERROR APPEARS FOR comp  

这指的是等式左侧的相同声明变量。您需要使其对局部变量使用不同的名称,或者在右侧使用 this.real*this.real。

于 2013-10-01T17:29:39.347 回答
0

好问题!在行中:

double real = real*real-comp*comp;

表达式中引用的真正real*real变量实际上是您刚刚声明的局部real变量,而不是real 您可能认为的对象的字段。局部变量在范围方面具有优先权。如果要引用该字段,则需要使用: this.real明确说明您正在谈论的范围。

例如:

double real = this.real * this.real - this.comp * this.comp;
double comp = 2 * this.real * this.comp;

或者,您可以通过为局部变量使用不同的名称来避免该问题,这样编译器就不会混淆:

double r = real * real - comp * comp;
double c = 2 * real * comp;
return new Complex(r, c);

或者您可以删除临时变量并将计算放在一行中:

public Complex square() { 
    return new Complex(real * real - comp * comp, 2 * real * comp);
}
于 2013-10-01T17:41:21.183 回答