我用Java编写代码,并且我不断从编译器中得到两个错误,说"找不到符号。"这是我的代码和错误。
public ComplexNumber(float a, float b){
a = real;
b = imaginary;
}
以下是两个错误。
ComplexNumber.java:22: error: cannot find symbol
a = real;
^
symbol: variable real
location: class ComplexNumber
ComplexNumber.java:23: error: cannot find symbol
b = imaginary;
^
symbol: variable imaginary
location: class ComplexNumber
2 errors
非常感谢任何建议。提前谢谢!
答案 0 :(得分:1)
您正在尝试访问不存在的变量real
和imaginary
。我认为你对参数有一般的误解。你想要的是这样的:
public class ComplexNumber
{
float real; // Attribute for the real part
float imaginary; // Attribute for the imaginary part
public ComplexNumber(float r, float i) // Constrctor with two parameters
{
real = r; // Write the value of r into real
imaginary = i; // Write the value of i into imaginary
}
public static void main(String[] args)
{
// Calling the constructor, setting real to 17 and immaginary to 42
ComplexNumber c = new ComplexNumber(17, 42);
System.out.println(c.real); // yielding 17
System.out.println(c.imaginary); // yielding 42
}
}
答案 1 :(得分:0)
所以我看到两个明显的错误,第一个是编译器告诉你的错误,即real
和imaginary
没有在任何地方声明。在Java中,除非先前已声明变量,否则不能使用变量。您可能希望拥有ComplexNumber
的真实和虚构组件,因此您需要适当地为其声明成员变量。
e.g。
public class ComplexNumber {
float real;
float imaginary;
...
第二个错误是您尝试将real
和imaginary
的值分配给参数变量,而不是相反。执行此操作时,您将丢弃传递给方法的数据而不是存储它:
public ComplexNumber(float a, float b){
a = real; // this overwrites the value of a instead of using it
b = imaginary; // this overwrites the value of b instead of using it
}
通常,Java中的约定是尝试为您的成员变量提供信息性名称,然后在构造函数,getter和setter中,使用带有this.
前缀的相同名称作为成员变量,以区别于参数。
大多数现代IDE都会以这种格式自动为您生成代码。
e.g。
public class ComplexNumber {
float real;
float imaginary;
public ComplexNumber(float real, float imaginary) {
this.real = real;
this.imaginary = imaginary;
}
}