2014-11-05 17 views
-8

我正在用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 ComplexNumber 
ComplexNumber.java:23: error: cannot find symbol 
    b = imaginary; 
     ^
symbol: variable imaginary 
location: class ComplexNumber 
2 errors 

任何意見是非常感謝。提前致謝!

+3

你的程序中定義了'real'和'imaginary'哪裏有? – 2014-11-05 20:57:14

+1

由於'real'和'imaginary'沒有在你的類中定義,我相信你應該把你的參數值分配給某個字段,而不是寫入它們。 – Habib 2014-11-05 20:57:45

回答

0

所以我看到兩個明顯的錯誤,其中第一個就是編譯器告訴你,即realimaginary沒有得到任何地方聲明。在Java中,除非先前已聲明它,否則不能使用變量。你可能想要有一個實際假想你的ComplexNumber的組件,所以你需要適當地聲明它的成員變量。

例如

public class ComplexNumber { 
    float real; 
    float imaginary; 
    ... 

第二個錯誤是,你想,而不是周圍的其他方式的realimaginary值分配給您的參數變量。當你這樣做,你是不是扔掉了在你的方法傳遞的數據存儲它的:

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將以這種格式自動生成您的代碼。

例如

public class ComplexNumber { 
    float real; 
    float imaginary; 

    public ComplexNumber(float real, float imaginary) { 
     this.real = real; 
     this.imaginary = imaginary; 
    } 
} 
1

您正試圖訪問不存在的變量realimaginary。我認爲你對參數有一個普遍的誤解。你需要的是這樣的:

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 
    } 
} 
相關問題