gpt4 book ai didi

java - Rectangle 类 Java

转载 作者:行者123 更新时间:2023-11-30 08:51:37 25 4
gpt4 key购买 nike

好的,这是作业。我终生无法弄清楚我在这里做错了什么。从“设置方法应验证长度和宽度都是大于 0.0 且小于 20.0 的 float ”一书中,我以为我有它但是当我运行测试时它只给了我面积和周长。

public class Rectangle {
private float width = 1;
private float length = 1;

public Rectangle(float userWidth, float userLength) {
width = userWidth;
length = userLength;

}

public void setWidth(float userWidth) {
if (userWidth < 0.0 || userWidth > 20.0) {
throw new IllegalArgumentException(Float.toString(width));
} else {
width = userWidth;
}
}

public float getWidth() {
return width;

}

public void setLength(float userLength) {
if (userLength < 0.0 || userLength > 20.0) {
throw new IllegalArgumentException(Float.toString(length));
} else {
length = userLength;
}
}

public float getLength() {
return length;
}

public float calcArea() {
return length * width;
}

public float calcPerimeter() {
return length + length + width + width;
}

}

我的测试代码是

import java.util.Scanner;


public class RectangleTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);

System.out.println("Enter the width");
float width = input.nextFloat();

System.out.println("Enter the length");
float length = input.nextFloat();

Rectangle myRectangle = new Rectangle(width, length);

System.out.printf("The area is: %.2f\n", myRectangle.calcArea());
System.out.printf("The perimeter is: %.2f\n",
myRectangle.calcPerimeter());

input.close();

}

}

最佳答案

当您使用Rectangle(float, float) 构造函数时,您并不是在使用增变器方法来执行验证。你可以做类似的事情

public Rectangle(float userWidth, float userLength) {
// width = userWidth;
// length = userLength;
setWidth(userWidth);
setLength(userLength);
}

这将调用您的“setter”。此外,还有一个微妙的(也是唯一潜在的)错误隐藏在

input.close();

因为 System.in 是一个全局变量,如果您将代码提取到一个方法中(然后尝试从其他任何地方读取 System.in),您可能会遇到意外行为).

关于java - Rectangle 类 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com