【问题描述】 编辑Person类,有两个double类型的私有成员变量weight、height,需要为每个成员变量设计get/set方法 注意: weight的准则是大于400或者小于0时,默认赋值70.0 height的准则是大于300或者小于0时,默
时间: 2024-10-18 11:09:59 浏览: 42
编辑`Person`类,你可以按照以下步骤创建双属性`weight`和`height`,并添加相应的getter和setter方法。同时,为了满足提供的条件,可以在setter方法中加入检查:
```java
public class Person {
private double weight;
// 默认值为70.0
private double height;
public Person() {
this.weight = validateWeight(70.0);
this.height = validateHeight(0.0);
}
// Getters and Setters with validation
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
if (weight <= 0 || weight > 400) {
System.out.println("Invalid weight, setting to default value 70.0");
this.weight = 70.0;
} else {
this.weight = weight;
}
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
if (height <= 0 || height > 300) {
System.out.println("Invalid height, setting to default value 0.0");
this.height = 0.0;
} else {
this.height = height;
}
}
// Validation methods
private double validateWeight(double defaultValue) {
return Math.max(defaultValue, Math.min(weight, 400));
}
private double validateHeight(double defaultValue) {
return Math.max(defaultValue, Math.min(height, 300));
}
}
```
在这个版本的`Person`类中,设置重量和高度时会先进行有效性检查,如果不符合条件,则自动采用默认值。
阅读全文