qq_27990751 2016-09-27 01:02 采纳率: 0%
浏览 1009

对象作为类的成员变量的程序设计

对象作为类的成员变量的程序设计。设计类Student和类Date, 其中Student的成员变量birthday是date类的对象,类Student的其他成员和类Date的成员按常规设计,特别要注意两个类的构造函数设计;在主函数中利用对象数组管理5个学生的数据,分别计算男生和女生的平均年龄并输出。

  • 写回答

1条回答 默认 最新

  • Veggiel 2016-09-27 01:33
    关注
     package com.a;
    
    public class Student {
    private String name;
    private int age;
    private Date birthday;
    private String gender;
    
    public Student(String name, int age, Date birthday, String gender) {
        super();
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.gender = gender;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", birthday=" + birthday + ", gender=" + gender + "]";
    }
    public Student() {
        super();
    }
    
    }
    
    
     package com.a;
    
    public class Date {
    private String birth;
    
    public String getBirth() {
        return birth;
    }
    
    public void setBirth(String birth) {
        this.birth = birth;
    }
    
    public Date(String birth) {
        super();
        this.birth = birth;
    }
    
    @Override
    public String toString() {
        return "Date [birth=" + birth + "]";
    }
    
    }
    
    
     package com.a;
    
    public class Test {
    public static void main(String[] args) {
        Student [] students = new Student[5];
        int boyAge = 0;
        int girlAge = 0;
        int flag = 0;
        for (int i = 0; i < students.length; i++) {
            if(i/2==0){
                students[i] = new Student("kim"+i, i+10, new Date("2000-12-12"),"男");
                boyAge +=students[i].getAge();
                flag++;
            }else{
                students[i] = new Student("kim"+i, i+10, new Date("2000-12-12"),"女");
                girlAge +=students[i].getAge();
            }
        }
        float boyAvgAge = boyAge/flag;
        float girlAvgAge = boyAge/(students.length-flag);
        System.out.println("男生的平均年龄为:"+boyAvgAge+"女生的平均年龄:"+girlAvgAge);
    }
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备