编辑:这本书有一个错字,圆柱体和使用的体积,但程序的重点是练习使用静态方法,所以没关系。
我完成了这个程序并让它工作以获取与我的主类交互的静态方法。我只是遇到了十进制格式的问题。双打我得到小数点后 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
}
}