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