1.创建JavaBean类
public class Friend {
//题目要求:定义数组存储4个朋友对象
//属性:姓名,年龄,性别,爱好
//计算出四位朋友的平均年龄
//统计出比平均年龄低的朋友有几个,并把信息都打印出来
private String name;
private int age;
private char gender;
private String hobby;
//构建标准的JavaBean类
//空参
public Friend() {
}
//全参
public Friend(String name, int age, char 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 char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
2.测试类
public class FriendTest {
public static void main(String[] args) {
//1.新建数组
Friend[] arr = new Friend[4];
//2.创建对象
Friend f1 = new Friend("张三", 18, '女', "唱歌");
Friend f2 = new Friend("李四", 20, '女', "跳舞");
Friend f3 = new Friend("王五", 23, '男', "rap");
Friend f4 = new Friend("赵六", 30, '男', "打篮球");
//3.存入数组中
arr[0] = f1;
arr[1] = f2;
arr[2] = f3;
arr[3] = f4;
//4.求平均值
int sum = 0;
for (int i = 0; i < arr.length; i++) {
Friend friend = arr[i];
sum = sum + friend.getAge();
}
int avg = sum / arr.length;
System.out.println("四位朋友年龄的平均值为:" + avg);
//5.统计年龄比平均值低的有几个,并打印信息
int count = 0;
for (int i = 0; i < arr.length; i++) {
Friend friend = arr[i];
if (friend.getAge() < avg) {
count++;
}
}
System.out.println("年龄比平均值低的共有" + count + "位");
//6.打印信息
System.out.println("分别为:");
for (int i = 0; i < arr.length; i++) {
Friend friend = arr[i];
if (friend.getAge() < avg) {
count++;
System.out.println(friend.getName() + ", " + friend.getAge() + ", " + friend.getGender() + ", " + friend.getHobby());
}
}
}
}
3.运行结果