2015-12-02 38 views
2

我有這段代碼,我缺少靜態字段。我如何在這個程序中做靜態字段?我是否也需要實例字段?如何做靜態方法?

import java.util.Scanner; 

public class Geometry 
{ 

    public static double sphereVolume(double r) 
    { 
     double svol=(4.0/3.0)*Math.PI*(Math.pow(r,3)); 
     return svol; 
    } 

    public static double sphereSurface(double r) 
    { 
     double ssur=4.0*Math.PI*(Math.pow(r,2)); 
     return ssur; 
    } 

    public static double cylinderVolume(double r, double h) 
    { 
     return (Math.PI*r*r*h); 
    } 

    public static double cylinderSurface(double r, double h) 
    { 
     double csur=2*(Math.PI*(Math.pow(r,2)))+(2*Math.PI*r)*h; 
     return csur; 
    } 

    public static double coneVolume(double r, double h) 
    { 
     return (Math.PI/3.0)*h*(Math.pow(r,2)); 
    } 

    public static double coneSurface(double r, double h) 
    { 
     return Math.PI*r*r+Math.PI*r*Math.sqrt(Math.pow(r,2)+(Math.pow(h,2))); 
    } 

    public static void main(String[] args) 
    { 
     Scanner in=new Scanner(System.in); 
     System.out.println("What is the radius?"); 
     String input=in.nextLine(); 
     double r=Double.parseDouble(input); 
     System.out.println("The volume of the sphere:"+sphereVolume(r)); 
     System.out.println("The Surface Area of the sphere:"+sphereSurface(r)); 

     System.out.println("The Surface Area of the sphere:"+cylinderSurface(r,h)); 
     System.out.println("The volume of the cone:"+coneVolume(r,h)); 
     System.out.println("The Surface Area of the cone:"+coneSurface(r,h)); 
    } 
} 
+1

靜態變量可以定義爲static double variablename; –

回答

0

因爲你在一個靜態背景下,沒有你們的幾何類的任何引用您需要指定這些方法都是從這樣的呼籲:

System.out.println("The volume of the sphere:"+Geometry.sphereVolume(r)); 
+0

它應該不重要,因爲主要方法已經在同一類中 – nafas

0

在發佈代碼的唯一問題是您沒有定義局部變量h,也沒有給用戶輸入值的機會。

你已經有很多這個類的靜態方法。 Geometry類是靜態方法的集合,它們沒有狀態(它們是無副作用的函數,每個函數都會返回從其輸入中計算出的值,而不會執行任何其他操作),並且我沒有看到任何理由將其混淆添加任何靜態字段或實例成員字段。你的靜態方法和主要方法最好使用局部變量,引入靜態變量只是通過允許方法引用共享狀態來提供錯誤的機會。

所有這些方法(包括main方法)都是同一類的靜態方法,因此在從此類中調用它們時,不需要使用類名作爲前綴。引用其他類中的某個方法時,您將使用類名。

0

您應該首先了解什麼是實例和靜態成員,然後您可以更好地理解並可以輕鬆地與語法相關聯。

實例成員/變量:內存按每個對象分配給它們。每當創建一個新對象時,該對象將包含所有實例變量作爲它的一部分。

靜態成員/變量:它們是基於每個類而不是基於每個對象的基礎上創建的。因此,爲了訪問它們,您只需要該類的名稱(ClassName.member)。在引用它們時不需要指定任何對象引用,因爲它們與Class相關聯而不是對象。

0

是的,對於靜態字段,您需要靜態關鍵字將字段與您聲明的類型相關聯。

private static double variable; 

不,你並不需要創建一個對象實例,創建對象實例,就像把所有實例的那個對象框,即這些領域現在屬於實例然而靜態字段屬於他們的類型關聯或聲明,這就是爲什麼Geometry.SomeVariable將具有與實例無關的相同字段。