定义数组存储 4 个女朋友的对象。女朋友的属性:姓名、年龄、性别、爱好;要求1:计算出四个女朋友的平均年龄;要求2:统计年龄比平均值低的女朋友有几个?并把他们的所有信息打印出来。
代码:
//对象数组 4
package demo01;
public class Girlfriends {private String name;private int age;private String gender;private String hobby;public Girlfriends() {}public Girlfriends(String name, int age, String gender, String hobby) {this.name = name;this.age = age;this.gender = gender;this.hobby = hobby;}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 String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getHobby() {return hobby;}public void setHobby(String hobby) {this.hobby = hobby;}
}
//对象数组 4
package demo01;
public class GirlfriendsDemo {public static void main(String[] args) {Girlfriends[] arr = new Girlfriends[4];Girlfriends g1 = new Girlfriends("小美", 18, "女", "唱歌");Girlfriends g2 = new Girlfriends("小红", 19, "女", "跳舞");Girlfriends g3 = new Girlfriends("小芳", 20, "女", "画画");Girlfriends g4 = new Girlfriends("小丽", 21, "女", "游泳");arr[0] = g1;arr[1] = g2;arr[2] = g3;arr[3] = g4;//计算四个女朋友的平均年龄:int sum = 0;for(int i = 0; i < arr.length; i++) {sum += arr[i].getAge();}double avg = (double)sum / arr.length;System.out.println("四个女朋友的平均年龄为:" + String.format("%.2f", avg));//统计年龄比平均值低的女朋友有几个?并把她们的所有信息打印出来:int count = 0;for(int i = 0; i < arr.length; i++) {if(arr[i].getAge() < avg) {count++;System.out.println(arr[i].getName() + "——————" + arr[i].getAge() + "——————" + arr[i].getGender() + "——————" + arr[i].getHobby());}}System.out.println("年龄比平均年龄低的女朋友有:" + count + "个!");}
}
运行结果: