java测量身体肥瘦指数公式:BMI值(BMI=体重/(身高*身高) BMI在18-25之间为标准。体重单位为公斤,身高单位为米 。 为了防止用户输入错误,请编写自定义异常类,一个是身高值XX不正常,一个是体重值不正确。 (1)请用户输入身高和体重,进行下面的判断: 当用户输入的身高超过2.5或小于0.5时,调用异常显示"身高输入错误, xxx不是合理的身高 当用户输入的体重超过300或小于20时,调用异常显示"体重输入错误, xxx不是合理的体重 如果正确,就输出他的身体BMI并输出标准还是肥胖还是偏瘦。 (2)定义一个Person类,里面有身高和体重成员变量,有一个BMI()计算他的BMI值,并有一个show()方法输出他的BMI和身高和体重情况。
时间: 2024-02-23 07:03:18 浏览: 240
好的,我会帮你解决这个问题。下面是实现代码:
自定义异常类:
```java
class HeightException extends Exception{
public HeightException(String msg){
super(msg);
}
}
class WeightException extends Exception{
public WeightException(String msg){
super(msg);
}
}
```
计算BMI值的方法:
```java
public static double calcBMI(double height, double weight) throws HeightException, WeightException{
if(height > 2.5 || height < 0.5){
throw new HeightException("身高输入错误," + height + "不是合理的身高");
}
if(weight > 300 || weight < 20){
throw new WeightException("体重输入错误," + weight + "不是合理的体重");
}
double bmi = weight / (height * height);
return bmi;
}
```
Person类:
```java
class Person{
private double height;
private double weight;
public Person(double height, double weight){
this.height = height;
this.weight = weight;
}
public double getHeight(){
return height;
}
public double getWeight(){
return weight;
}
public double calcBMI() throws HeightException, WeightException{
return calcBMI(height, weight);
}
public void show() throws HeightException, WeightException{
double bmi = calcBMI();
System.out.println("身高:" + height + "m,体重:" + weight + "kg,BMI值为:" + bmi);
if(bmi < 18){
System.out.println("偏瘦");
}else if(bmi >= 18 && bmi <= 25){
System.out.println("标准");
}else{
System.out.println("肥胖");
}
}
}
```
测试代码:
```java
public static void main(String[] args) {
double height = 1.7;
double weight = 65;
try{
Person p = new Person(height, weight);
p.show();
}catch(HeightException e){
System.out.println(e.getMessage());
}catch(WeightException e){
System.out.println(e.getMessage());
}
}
```
这样,当用户输入不合法的身高或体重时,就会抛出自定义的异常并提示用户,如果输入合法,就会输出BMI值和体型情况。
阅读全文