Java 自定义学生类:包含姓名,年龄,成绩属性.私有成员变量,生成无参,有参构造方法,生成get/set方法. 创建5个学生放到ArrayList中.使用迭代器获取每个学生信息.统计总分,平均分,最高分,最低分并输出
时间: 2024-05-09 18:17:27 浏览: 91
好的,我可以回答这个问题。以下是Java代码:
```
import java.util.ArrayList;
import java.util.Iterator;
public class Student {
private String name;
private int age;
private double grade;
public Student() {}
public Student(String name, int age, double grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getGrade() {
return grade;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGrade(double grade) {
this.grade = grade;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Tom", 20, 80));
students.add(new Student("Jerry", 21, 90));
students.add(new Student("Alice", 19, 70));
students.add(new Student("Bob", 22, 85));
students.add(new Student("Lily", 18, 95));
Iterator<Student> iterator = students.iterator();
double sum = 0;
double maxGrade = Double.MIN_VALUE;
double minGrade = Double.MAX_VALUE;
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println("Name: " + student.getName() +
", Age: " + student.getAge() +
", Grade: " + student.getGrade());
sum += student.getGrade();
maxGrade = Math.max(maxGrade, student.getGrade());
minGrade = Math.min(minGrade, student.getGrade());
}
double average = sum / students.size();
System.out.println("Total grade: " + sum);
System.out.println("Average grade: " + average);
System.out.println("Max grade: " + maxGrade);
System.out.println("Min grade: " + minGrade);
}
}
```
运行后,输出结果为:
```
Name: Tom, Age: 20, Grade: 80.0
Name: Jerry, Age: 21, Grade: 90.0
Name: Alice, Age: 19, Grade: 70.0
Name: Bob, Age: 22, Grade: 85.0
Name: Lily, Age: 18, Grade: 95.0
Total grade: 420.0
Average grade: 84.0
Max grade: 95.0
Min grade: 70.0
```
阅读全文