对象作为类的成员变量的程序设计。设计类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); } }
解决 无用评论 打赏 举报