JAVA编程 详细
发布网友
发布时间:2022-04-21 19:56
我来回答
共1个回答
热心网友
时间:2023-06-06 22:25
灞曞紑鍏ㄩ儴Student 绫伙細
public class Student {
public String name;
private String sex;
private int height;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
HeightAvg 绫伙細
import java.util.ArrayList;
import java.util.List;
public class HeightAvg {
public static int getAvg(List<Student> studentList) {
int avgValue = 0;
int sumValue = 0;
int countNum = 0;
countNum = studentList.size();
for (int i = 0; i < countNum; i++) {
sumValue = sumValue + studentList.get(i).getHeight();
}
if (countNum == 0) {
avgValue = 0;
} else {
avgValue = sumValue / countNum;
}
return avgValue;
}
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
Student student1 = new Student();
student1.setHeight(10);
Student student2 = new Student();
student2.setHeight(20);
Student student3 = new Student();
student3.setHeight(30);
Student student4 = new Student();
student4.setHeight(40);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
int avgValue =getAvg(studentList);
System.out.println(avgValue);
}
}