編輯:該書有一個錯誤的圓柱體和使用體積代替,但程序的重點是鍛鍊靜態方法的工作,所以沒關係。靜態方法的十進制格式化
我完成了這個程序,並得到它的工作,以獲得靜態方法與我的主類進行交互。我只是有十進制格式的問題。雙打我得到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
}
}
工作。謝謝! 我改變 'Area.Area(cylinderRadius,cylinderHeight)' 到 'df.format(Area.Area(cylinderRadius,cylinderHeight))' 等 – iamgod