2011-09-17 116 views
5

我們正在學習如何在Java使用多個類,現在,有一個項目,詢問有關創建類Circle其中將包含一個radiusdiameter,然後引用它從主類找到直徑。此代碼繼續收到錯誤(在標題中提到的)Java錯誤 - 「無效的方法聲明,要求返回類型」

public class Circle 
{ 
    public CircleR(double r) 
    { 
     radius = r; 
    } 
    public diameter() 
    { 
     double d = radius * 2; 
     return d; 
    } 
} 

感謝您的幫助,-AJ

更新1: 好吧,但我不應該申報的第三行public CircleR(double r)作爲一個雙重的,對嗎?在我學習的書中,這個例子並沒有這樣做。

public class Circle 

    { 
     //This part is called the constructor and lets us specify the radius of a 
     //particular circle. 
     public Circle(double r) 
     { 
     radius = r; 
     } 

     //This is a method. It performs some action (in this case it calculates the 
     //area of the circle and returns it. 
     public double area() //area method 
     { 
      double a = Math.PI * radius * radius; 
     return a; 
    } 

    public double circumference() //circumference method 
    { 
     double c = 2 * Math.PI * radius; 
    return c; 
    } 

     public double radius; //This is a State Variable…also called Instance 
     //Field and Data Member. It is available to code 
    // in ALL the methods in this class. 
    } 

正如你看到的,代碼public Circle(double r)....如何是從我在我做了與public CircleR(double r)有什麼不同?無論出於何種原因,本書的代碼中都沒有提供任何錯誤,但是我說這裏有錯誤。

+3

Javac通常很有用,它返回的錯誤信息非常清晰。下一次你有其中一個有短暫的休息時間,答案就會發生在你:) – mbatchkarov

+2

'CircleR'不是'Circle'的構造函數。名稱*必須匹配。 – 2011-09-17 01:17:13

回答

22

正如你看到的,代碼公開的社交圈(雙R)......怎麼是 從我在我做了與公共CircleR(雙R)有什麼不同?對於 無論什麼原因,本書的代碼中沒有錯誤,但 我說那裏有錯誤。

當定義一個類的構造函數時,它們應該與它的類具有相同的名稱。 因此下面的代碼

public class Circle 
{ 
    //This part is called the constructor and lets us specify the radius of a 
    //particular circle. 
    public Circle(double r) 
    { 
    radius = r; 
    } 
.... 
} 

是正確的,而你的代碼

public class Circle 
{ 
    private double radius; 
    public CircleR(double r) 
    { 
     radius = r; 
    } 
    public diameter() 
    { 
     double d = radius * 2; 
     return d; 
    } 
} 

是錯誤的,因爲你的構造函數從它的類不同的名稱。您既可以遵循本書相同的代碼,並從

public CircleR(double r) 

改變你的構造函數,

public Circle(double r) 

或者(如果你真的想命名構造函數CircleR)類重命名爲CircleR。

所以你的新類應該是

public class CircleR 
{ 
    private double radius; 
    public CircleR(double r) 
    { 
     radius = r; 
    } 
    public double diameter() 
    { 
     double d = radius * 2; 
     return d; 
    } 
} 

我還添加了返回類型雙您的方法,通過升級Froyo和John B.

參考指出這article有關構造函數。

HTH。

+0

好的,但現在它突出顯示的半徑= r;部分和說「找不到符號 - 變量類」。感謝這篇文章,我現在正在閱讀它。 –

+1

沒關係,我意識到在底部,我需要說公開的雙半徑;。這是什麼原因呢?爲什麼我要在公共圈內部(而不是在公共圈內部)說明這一點? –

+0

因爲...'double r'是構造函數的參數。除了任何方法之外,'雙半徑'是班級中的一個領域。當方法返回時,參數將被丟棄。只要類實例存在字段。 –

4

你忘了申報雙重作爲返回類型

public double diameter() 
{ 
    double d = radius * 2; 
    return d; 
} 
8

每個方法(除了構造函數等)都必須有一個返回類型。

public double diameter(){... 
-1

向main方法中添加類時,我遇到了類似的問題。原來,這不是一個問題,這是我沒有檢查我的拼寫。所以,作爲一個noob,我瞭解到,拼寫錯誤會導致混亂。這些帖子幫助我「看到」我的錯誤,現在一切都很好。

相關問題