定义一个Person类,在该类中定义姓名,年龄等私有成员变量,并对成员变量定义set和get方法;定义printMSG()方法,实现对类中成员变量的输出;定义computeBMI()方法实现接受体重和身高的输入,并计算体质指数(体质指数(BMI)=体重(kg)/身高(m)^2),根据计算出的体质指数,提出建议(仅供参考),比如BMI低于20,输出“过轻建议补充营养”;20-25输出“适中请继续保持”,>26输出“过重,建议加强锻炼并合理控制饮食”。定义Person类的对象,实现调用其成员方法 使用java编写
时间: 2023-02-09 22:46:31 浏览: 316
get和set方法示例-Java项目实战精编
以下是使用 Java 编写的 Person 类的代码示例:
```
public class Person {
private String name;
private int age;
private double weight;
private double height;
public Person(String name, int age, double weight, double height) {
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public void printMsg() {
System.out.println("姓名: " + name + ", 年龄: " + age + ", 体重: " + weight + ", 身高: " + height);
}
public void computeBMI() {
double bmi = weight / (height * height);
if (bmi < 20) {
System.out.println("过轻建议补充营养");
} else if (bmi >= 20 && bmi <= 25) {
System.out.println("适中请继续保持");
} else {
System.out.println("过重,建议加强锻炼并合理控制饮食");
}
}
}
```
要使用该类,你需要创建一个 Person 对象,然后调用它的成员方法。例如:
```
Person p = new Person("张三", 20, 65.0, 1.75);
p.printMsg();
p.computeBMI();
```
上面的代码会输出:
```
姓名: 张三, 年龄: 20, 体重: 65.0, 身高: 1.75
适中请继续保持
```
阅读全文