我正在做一个家庭作业,我确定一个圆柱体的体积。本课的对象是类和对象。我有两个课程,“CylinderTest”和“Cylinder”。气缸测试调用气缸。到目前为止,除了 get 和 set 方法外,一切似乎都在工作。我试图阻止对负数的计算,但这不起作用,它无论如何都会执行计算。
这是 CylinderTest 类
public class CylinderTest
{
public static void main(String[] args)
{
Cylinder myTest = new Cylinder(-1, -1);
myTest.getHeight();
myTest.getRadius();
System.out.println(myTest);
printHeader();
double volume = myTest.volume();
displayCylinder(volume);
}
private static void printHeader()
{
System.out.println("Cylinder");
System.out.println("________");
}
private static void displayCylinder(double volume)
{
System.out.print("Cylinder volume = ");
System.out.println(volume);
}
}
这是气缸类
public class Cylinder
{
// variables
public static final double PI = 3.14159;
private double radius, height, volume;
// constructor
public Cylinder(double radius, double height)
{
this.radius = radius;
this.height = height;
}
// Volume method to compute the volume of the cylinder
public double volume()
{
return PI * radius * radius * height;
}
// accessors and mutators (getters and setters)
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
if (radius > 0.0)
this.radius = radius;
else
this.radius = 1.0;
}
public double getHeight()
{
return height;
}
public void setHeight(double height)
{
if (height > 0.0)
this.height = height;
else
this.height = 1.0;
}
public double getVolume()
{
return volume;
}
public void setVolume(double volume)
{
this.volume = volume;
}
}