大家好,今天来分享新的基础小案例啦~
定义一个存放学生的集合
(1)学生类中有 姓名,身高两个属性
(2)集合中保存五个学生对象
(3)求所有学生的平均身高和最高身高
首先创建一个学生类:定义两个属性,姓名和身高
public class Student {
private String name;
private Double height;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Student(String name, Double height) {
super();
this.name = name;
this.height = height;
}
public Student() {
// TODO Auto-generated constructor stub
}
}
然后写个main方法测试一下哦~
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("王1", 165.0));
list.add(new Student("王2", 175.0));
list.add(new Student("王3", 185.0));
list.add(new Student("王4", 155.0));
list.add(new Student("王5", 195.0));
double avgHeight = 0.0;
double maxHeight = 0.0;
double sumHeight = 0.0;
for (int i = 0; i < list.size(); i++) {
// maxHeight = list.get(i).getHeight();
sumHeight += list.get(i).getHeight();
if (maxHeight < list.get(i).getHeight()) {
maxHeight = list.get(i).getHeight();
}
}
avgHeight = sumHeight / list.size();
System.out.println("平均身高:" + avgHeight);
System.out.println("最高身高:" + maxHeight);
}
效果图如下:
这次分享结束了,拜拜咯~