使用Java测量身体肥瘦指数公式,可多次输入输出BMI值:BMI值(BMI=体重/(身高*身高) BMI在18-25之间为标准。体重单位为公斤,身高单位为米 。 为了防止用户输入错误,请编写自定义异常类,一个是身高值XX不正常,一个是体重值不正确。 (1)请用户输入身高和体重,进行下面的判断: 当用户输入的身高超过2.5或小于0.5时,调用异常显示"身高输入错误, xxx不是合理的身高 当用户输入的体重超过300或小于20时,调用异常显示"体重输入错误, xxx不是合理的体重 如果正确,就输出他的身体BMI并输出标准还是肥胖还是偏瘦。 (2)定义一个Person类,里面有身高和体重成员变量,有一个BMI()计算他的BMI值,并有一个show()方法输出他的BMI和身高和体重情况。
时间: 2024-02-24 16:00:19 浏览: 16
好的,以下是实现你的要求的Java代码:
自定义异常类:
```java
class HeightException extends Exception {
public HeightException(String message) {
super(message);
}
}
class WeightException extends Exception {
public WeightException(String message) {
super(message);
}
}
```
计算BMI值和判断是否合理:
```java
import java.util.Scanner;
class BMI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double height, weight;
while (true) {
try {
System.out.print("请输入身高(米):");
height = scanner.nextDouble();
if (height > 2.5 || height < 0.5) {
throw new HeightException("身高输入错误," + height + "不是合理的身高");
}
break;
} catch (HeightException e) {
System.out.println(e.getMessage());
}
}
while (true) {
try {
System.out.print("请输入体重(公斤):");
weight = scanner.nextDouble();
if (weight > 300 || weight < 20) {
throw new WeightException("体重输入错误," + weight + "不是合理的体重");
}
break;
} catch (WeightException e) {
System.out.println(e.getMessage());
}
}
double bmi = weight / (height * height);
System.out.println("您的BMI是:" + bmi);
if (bmi < 18) {
System.out.println("您的体重偏轻");
} else if (bmi >= 18 && bmi <= 25) {
System.out.println("您的体重正常");
} else {
System.out.println("您的体重偏重");
}
}
}
```
Person类的实现:
```java
class Person {
private double height;
private double weight;
public Person(double height, double weight) {
this.height = height;
this.weight = weight;
}
public double BMI() {
return weight / (height * height);
}
public void show() {
double bmi = BMI();
System.out.println("身高:" + height + "米");
System.out.println("体重:" + weight + "公斤");
System.out.println("BMI:" + bmi);
if (bmi < 18) {
System.out.println("您的体重偏轻");
} else if (bmi >= 18 && bmi <= 25) {
System.out.println("您的体重正常");
} else {
System.out.println("您的体重偏重");
}
}
}
```
测试代码:
```java
class TestPerson {
public static void main(String[] args) {
Person person = new Person(1.75, 65);
person.show();
}
}
```
输出结果:
```
身高:1.75米
体重:65.0公斤
BMI:21.22
您的体重正常
```