2013-06-25 31 views
0

編輯:該書有一個錯誤的圓柱體和使用體積代替,但程序的重點是鍛鍊靜態方法的工作,所以沒關係。靜態方法的十進制格式化

我完成了這個程序,並得到它的工作,以獲得靜態方法與我的主類進行交互。我只是有十進制格式的問題。雙打我得到11位小數。我嘗試過使用DecimalFormat,但是沒有任何影響,不管我放在哪裏。由於現在使用靜態方法,我是否需要額外做些事情?

import java.text.DecimalFormat; //import DecimalFormat 

class Area{ 

    //Area of a Circle 
    static double Area(double radius){ 
     return Math.PI * (radius * radius); 
    } 

    //Area of a Rectangle 
    static int Area(int width, int length){ 
     return width * length; 
    } 

    //Volume of a Cyclinder 
    static double Area(double radius, double height){ 
     return Math.PI * (radius * radius) * height; 
    } 
} 

public class AreaDemo{ 
    public static void main(String[] args){ 

     //Variable Declarations for each shape 
     double circleRadius = 20.0; 
     int rectangleLength = 10; 
     int rectangleWidth = 20; 
     double cylinderRadius = 10.0; 
     double cylinderHeight = 15.0; 

     //Print Statements for the Areas 
     System.out.println("The area of a circle with a radius of " + circleRadius + " is " + Area.Area(circleRadius)); //Circle 
     System.out.println("The area of a rectangle with a length of " + rectangleLength + " width of " + rectangleWidth + " is " + Area.Area(rectangleLength, rectangleWidth)); //Rectangle 
     System.out.println("The area of a cylinder with radius " + cylinderRadius + " and height " + cylinderHeight + " is " + Area.Area(cylinderRadius, cylinderHeight)); //Cylinder 
    } 
} 

回答

1

如果你想使用你可以像這樣一個DecimalFormat,

double d = 1.234567; 
DecimalFormat df = new DecimalFormat("#.##"); 
System.out.print(df.format(d)); 

這將打印出1.23。如果增加格式"#.###這將是1.235

或多個適用於你會

DecimalFormat df = new DecimalFormat("#.##"); 
//Print Statements for the Areas 
System.out.println("The area of a circle with a radius of " + df.format(circleRadius) + " is " + df.format(Area.Area(circleRadius))); //Circle 
// do same for your others 
+0

工作。謝謝! 我改變 'Area.Area(cylinderRadius,cylinderHeight)' 到 'df.format(Area.Area(cylinderRadius,cylinderHeight))' 等 – iamgod

0

還有就是你decimal formatStatic methods

和控制浮點精度之間沒有關係算術,您應該使用java.math.BigDecimal.

或使用Decimal Format with Pattern

+0

浮點和雙精度被設計爲可使用在數學計算中。在處理貨幣或金錢時,您使用BigDecimal,而精確度很重要。 –

+0

@GilbertLeBlanc同意吉爾,我通知並添加了他的要求的十進制格式模式構造函數。 –