2015-09-27 181 views
0

我正在爲我的Java I類開發一個項目。我已經包含了我編寫的程序。我的公式似乎正在工作,但我的輸出不是。這是項目 - 「寫一個名爲Sphere的類,其中包含表示球體直徑的實例數據。定義球體構造函數以接受並初始化直徑,幷包括直徑的getter和setter方法。包含計算並返回體積和曲面的方法。包含一個toString方法,該方法返回球體的單行描述。創建一個名爲Multisphere一個驅動程序類,其主要方法instantites並更新幾個球對象「 這裏是我寫:使用java計算體積和表面積

public class Sphere 
{ 

    private double diameter; 
    private double calcVol; 
    private double calcSA; 


    //---------------------------------------------------------------------------------------------- 
    //Constructor 
    //---------------------------------------------------------------------------------------------- 

    public Sphere(double diameter) 
    { 
    this.diameter = diameter; 
    } 
    public void setDiameter(double diameter) 
    { 
    this.diameter = diameter; 
    } 
    public double getDiameter(double diameter) 
    { 
    return diameter; 
    } 
    public double calcVol() 
    { 
    return ((Math.PI) * (Math.pow(diameter, 3.0)/6.0)); 
    } 
    public double calcSA() 
    { 
    return ((Math.PI) * Math.pow(diameter, 2.0)); 
    } 
    public String toString() 
    { 
    return "Diameter: " + diameter + " Volume: " + calcVol + " Surface Area: " + calcSA; 
    } 
} 

public class MultiSphere 
{ 

    public static void main(String[] args) 
    { 


    Sphere sphere1 = new Sphere(6.0); 
    Sphere sphere2 = new Sphere(7.0); 
    Sphere sphere3 = new Sphere(8.0);d 



    sphere1.calcVol(); 
    sphere2.calcVol(); 
    sphere3.calcVol(); 

    sphere1.calcSA(); 
    sphere2.calcSA(); 
    sphere3.calcSA(); 

    System.out.println(sphere1.toString()); 

    System.out.println(sphere2.toString()); 

    System.out.println(sphere3.toString()); 
    } 
} 
+0

提示:你不應該有'calcVol '和'calcSA'變量。改爲調用方法。而您對這些方法的單獨調用將不起作用,因爲返回值不會在任何地方發生。 – RealSkeptic

回答

0
private double calcVol; 
private double calcSA; 

這些是您應該刪除的行,您聲明瞭與您也有的方法具有相同名稱的新字段。

toString你應該打電話給你的方法是這樣

return "Diameter: " + diameter + " Volume: " + calcVol() + " Surface Area: " + calcSA(); 

也在你main()您有這行的末尾一個額外d

Sphere sphere3 = new Sphere(8.0);d 
1

包括計算並傳回體積和表面是球面的方法。

這是你家庭作業中重要的一行。沒有提及球體的體積和表面積的內部狀態,所以爲此保留字段值是沒有意義的。你的方法是正確的,但你的toString應該只是調用這些方法:

public String toString() 
{ 
    return "Diameter: " + diameter + " Volume: " + calcVol() + " Surface Area: " + calcSA(); 

} 

這樣,你不需要先調用方法和你toString將永遠代表最新的表面積和體積,應直徑變化。