局部变量real可能尚未初始化

时间:2013-10-01 17:26:23

标签: java

我已经为复数编写了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");
    }
}

3 个答案:

答案 0 :(得分: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,这是未初始化的,因而是错误。

答案 1 :(得分: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。

答案 2 :(得分:0)

好问题!在该行:

double real = real*real-comp*comp;

real*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);
}