用java语言定义一个人的类,并且创建一个人的对象,输入人的身高和体重,计算其BMI指标,并且判断他的体重正常范围,并且判断他是超重偏瘦还是正常
时间: 2024-11-15 07:27:04 浏览: 2
在Java中,我们可以定义一个名为Person的类,包含姓名、身高和体重属性,以及相应的getters和setters方法。同时,我们还会添加一个计算BMI(身体质量指数)的方法,以及一个根据BMI值判断体重状况的方法。以下是简单的代码示例:
```java
public class Person {
private String name;
private double heightMeters;
private double weightKg;
// getters and setters for name, height, and weight
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getHeightMeters() { return heightMeters; }
public void setHeightMeters(double heightMeters) { this.heightMeters = heightMeters; }
public double getWeightKg() { return weightKg; }
public void setWeightKg(double weightKg) { this.weightKg = weightKg; }
// Calculate BMI method
public double calculateBMI() {
if (heightMeters <= 0 || weightKg <= 0) {
throw new IllegalArgumentException("Invalid height or weight");
}
return weightKg / (heightMeters * heightMeters);
}
// Method to determine weight status based on BMI
public String determineWeightStatus() {
double bmi = calculateBMI();
if (bmi < 18.5) {
return "超轻或偏瘦";
} else if (bmi >= 18.5 && bmi < 24) {
return "正常";
} else if (bmi >= 24 && bmi < 28) {
return "超重";
} else {
return "肥胖";
}
}
}
// 使用示例
public static void main(String[] args) {
Person person = new Person();
person.setName("张三");
person.setHeightMeters(1.75); // 以米为单位
person.setWeightKg(70); // 以公斤为单位
double bmi = person.calculateBMI();
System.out.println("BMI: " + bmi);
System.out.println("Weight Status: " + person.determineWeightStatus());
}
```
阅读全文