Java 局部变量real可能尚未初始化
我已经为复数编写了complex.java代码。但它在eclipse上给出了错误“局部变量real可能尚未初始化”。不知道怎么了。代码如下。任何帮助都将不胜感激Java 局部变量real可能尚未初始化,java,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;
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");
}
}
您需要在该语句的右侧使用
this.real
和this.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
,它尚未初始化,因此会出现错误
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。好问题!行中:
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);
}
如果您只是阅读错误语句,您认为这意味着什么?因为这是一个不可变的对象(好主意!)为了清晰起见,最好将real和comp这两个字段设置为final。