(一)汽车数组练习
一、题目:
定义数组存储3部手机对象。
手机的属性:品牌,价格,颜色。
要求,计算出三部手机的平均价格。
二、重难点:
小数点保留(BigDecimal可用)
三、代码:
1)汽车bean
public class Phone {
/*
* 定义数组存储3部手机对象。
* 手机的属性:品牌,价格,颜色。
* 要求,计算出三部手机的平均价格。
* */
private String brand;
private int price;
private String color;
public Phone() {
}
public Phone(String brand, int price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
2)汽车数组
public class PhoneTest {
public static void main(String[] args) {
//1.创建一个数组
Phone[] arr = new Phone[3];
//2.创建手机的对象
Phone p1 = new Phone("小米", 2000, "白色");
Phone p2 = new Phone("华为", 3000, "红色");
Phone p3 = new Phone("苹果", 4000, "紫色");
//3.把手机对象添加到数组当中
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
//4.获取三部手机的平均价格
int sum = 0;
for (int i = 0; i < arr.length; i++) {
Phone phone = arr[i];
sum = sum + phone.getPrice();
}
//5.求平均值
int avg = sum / arr.length;
double avg2 = sum * 1.0 / arr.length;
System.out.println(avg2);
}
}
(二)学生数组练习
一、题目:
定义数组存储4个学生的对象。
学生属性:姓名、年龄、性别、爱好。
要求1:计算出4个学生的平均年龄
要求2:统计年龄比平均值低的学生有几个?并把他们的所有信息打印出来。
二、重难点:
数组求平均值和最值、统计个数。
三、代码:
1)学生bean
public class Student {
/*
* 定义数组存储4个学生的对象。
* 学生属性:姓名、年龄、性别、爱好。
* 要求1:计算出4个学生的平均年龄
* 要求2:统计年龄比平均值低的学生有几个?并把他们的所有信息打印出来。
* */
private String name;
private int age;
private String gender;
private String hobby;
public Student() {
}
public Student(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;
}
}
2)学生数组
public class StudentTest {
public static void main(String[] args) {
//1.定义数组存入学生的对象
Student[] arr = new Student[4];
//2.创建学生对象
Student s1 = new Student("小红", 19, "女", "看电影");
Student s2 = new Student("小明", 20, "男", "看书");
Student s3 = new Student("小花", 21, "女", "运动");
Student s4 = new Student("小天", 22, "男", "吃饭");
//3.把对象添加到数组中
arr[0] = s1;
arr[1] = s2;
arr[2] = s3;
arr[3] = s4;
//4.求和
int sum = 0;
for (int i = 0; i < arr.length; i++) {
Student s = arr[i];
sum = sum + s.getAge();
}
//5.平均值
int avg = sum / arr.length;
//6.统计年龄比平均值低的有几个,打印他们的信息
int count = 0;
for (int i = 0; i < arr.length; i++) {
Student s = arr[i];
if (s.getAge() < avg) {
count++;
System.out.println(s.getName() + "," + s.getAge() + "," + s.getGender() + "," + s.getHobby());
}
}
System.out.println("年龄比平均值低的有" + count + "个");
}
}