使用实例变量length和width创建一个Rectangle类,以 两者的默认值均为1。这个班应该有 合适的set和get方法来访问其实例变量。的 设置方法应验证是否为长度和宽度分配了一个 大于0.0且小于20.0的值,请提供 适当的公共方法来计算矩形的周长,以及 区域。编写合适的类“ RectangleTest”以测试Rectangle 课。
我想到的是什么
package rectangle;
public class Rectangle
{
private double width;
private double length;
public Rectangle()
{
width=1;
length=1;
}
public Rectangle(double width, double length)
{
this.width = width;
this.length = length;
}
public void setWidth(float width)
{
this.width = width;
}
public float getWidth()
{
return (float) width;
}
public void setLength(float length)
{
this.length = length;
}
public float getLength()
{
return (float) length;
}
public double getPerimeter()
{
return 2 * (width + length);
}
public double getArea()
{
return width * length;
}
}
package rectangle;
import java.util.Scanner;
public class RectangleTest extends Rectangle
{
public static void main(String[] args)
{
Scanner RectangleTest = new Scanner(System.in);
System.out.print("Length: ");
float lengthInput = RectangleTest.nextFloat();
System.out.print("Width: ");
float widthInput = RectangleTest.nextFloat();
Rectangle rectangle = new Rectangle (lengthInput, widthInput);
System.out.printf("Perimeter: %f%n",
rectangle.getPerimeter());
System.out.printf("Area: %f%n",
rectangle.getArea());
}
}
代码很好,只是我不确定如何在不破坏所有内容的情况下实现0-20之间的值,并尝试了不同的方法。
答案 0 :(得分:1)
我会检查它,如果值无效,则抛出IllegalArgumentException
,例如:
public void setLength(float length) {
if (length <= 0f || length >= 20.0f) {
throw new IllegalArgumentException("Invalid length " + length);
}
this.length = length;
}