我正在做一项家庭作业,确定圆柱体的体积。本课的对象是类和对象。我有两个课程,“CylinderTest”和“Cylinder”。 Cylinder 测试调用 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);
}
}
这是 Cylinder 类
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;
}
}
在构造函数中,您需要使用与 getter 和 setter 中相同的测试,而不是直接设置值。目前,您可以使用
new Cylinder(-1,-1)
规避 setter 中的测试。
你的构造函数应该调用你的setter,并且你应该检查setter中的逻辑。如果调用代码传递负值,您真的想继续使用值 1 吗?
你可以摆脱你的构造函数并使用:
Cylinder myTest = new Cylinder();
myTest.setHeight(-1);
myTest.setRadius(-1);
或者,您可以创建一个“工厂”方法:
public static Cylinder createCylinder(double radius, double height)
{
Cylinder tmp = new Cylinder();
tmp.setRadius(radius);
tmp.setHeight(height);
}
虽然不推荐,但从语法上讲,您也可以更改构造函数来调用设置器。它看起来像这样:
public Cylinder(double radius, double height)
{
setRadius(radius);
setHeight(height);
}
为什么这被认为是不好的做法,请参阅:Java 从基本构造函数调用基本方法
除了不在构造函数中执行测试之外,您也不设置音量(任何时候它都为空)。
因此,将构造函数更改为:
public Cylinder(double radius, double height)
{
this.setRadius(radius);
this.setHeight(height);
this.volume = volume();
}
并且 删除
setVolume()
并将 setHeight()
和 setRadius()
设为私有。
您的 setter 方法没有进行验证,因为您根本没有调用它们。正如其他人评论的那样,一个好主意是在构造函数中调用它们,而不是直接向
radius
和 height
赋值。
像您一样初始化圆柱体的属性本身并没有错。但是,由于您需要运行“<=0" validation on your input, and your setters already implement this calling them is a simple solution.
一些额外的注释不会影响您正在寻找的结果,但仍然跳到我这里:
TestCylinder
中,您调用了两个 getter 方法,但没有将它们分配给任何内容。请记住,getter 返回一个值,因此单独调用它们实际上不会执行任何操作。TestCylinder
中,您可以直接调用Cylinder.volume()
,而不是使用其getter方法getVolume
来获取圆柱体的体积。在这里,我建议要么将计算体积的逻辑放在 getter 上并仅使用该方法,要么让 getter 调用 volume()
,以防您在 Cylinder
类的另一部分需要后者。