为什么我的编译器在Java中给我这两个错误?
我正在用Java编写一个代码,我不断从编译器那里得到两个错误,说“找不到符号”。这是我的代码和错误为什么我的编译器在Java中给我这两个错误?,java,Java,我正在用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 Com
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
非常感谢您的建议。提前谢谢 您正试图访问不存在的变量
real
和virtual
。我认为你对参数有一个普遍的误解。你想要的是这样的:
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
}
}
因此,我看到两个明显的错误,第一个是编译器告诉您的,即
real
和virtual
没有在任何地方声明。在Java中,除非事先声明了变量,否则不能使用它。您可能希望在您的ComplexNumber
中有一个实的和虚的组件,因此您需要为它适当地声明成员变量
e、 g
第二个错误是,您试图将实
和虚
的值分配给参数变量,而不是反过来分配。执行此操作时,您将丢弃传递到方法中的数据,而不是将其存储:
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
在你的程序中,
real
和virtual
在哪里定义?因为real
和virtual
在你的类中没有定义,而且我认为你应该把参数值赋给某个字段,而不是写得太多。
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
}
public class ComplexNumber {
float real;
float imaginary;
public ComplexNumber(float real, float imaginary) {
this.real = real;
this.imaginary = imaginary;
}
}