在Java中,你可以使用数组来存储多个对象。根据你提供的信息,这里是一个简单的例子,展示如何使用数组定义一个`People`类的对象:
import java.util.Scanner;class People {String name;double height;double weight;// 构造方法People() {// 初始化成员变量name = "";height = 0.0;weight = 0.0;}// 构造方法,通过参数赋初值People(String name, double height, double weight) {this.name = name;this.height = height;this.weight = weight;}// 成员方法,判断体重是否标准int check() {double referenceWeight = 110 + 5; // 参考体重为110cm身高时,加减5kgif (weight > referenceWeight) {return 1; // 过胖} else if (weight < referenceWeight - 5) {return -1; // 过瘦} else {return 0; // 标准}}}public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);People students[] = new People; // 创建一个包含5个People对象的数组System.out.println("请输入5位同学的信息:");for (int i = 0; i < 5; i++) {students[i] = new People(); // 创建People对象并赋值students[i].name = input.next(); // 输入姓名students[i].height = input.nextDouble(); // 输入身高students[i].weight = input.nextDouble(); // 输入体重}// 输出标准、过胖或过瘦的人数int standardCount = 0;int overweightCount = 0;int underweightCount = 0;for (int i = 0; i < 5; i++) {int result = students[i].check();if (result == 0) {standardCount++;} else if (result == 1) {overweightCount++;} else {underweightCount++;}}System.out.println("标准人数:" + standardCount);System.out.println("过胖人数:" + overweightCount);System.out.println("过瘦人数:" + underweightCount);}}
这段代码首先定义了一个`People`类,包含姓名、身高和体重三个成员变量,以及相应的构造方法和`check`方法。然后在`main`方法中,创建了一个`People`类型的数组,并通过循环输入5个学生的信息,最后统计并输出标准、过胖和过瘦的人数。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/129767.html