1. 程式人生 > 其它 >建立10個學生物件存入Collection集合中

建立10個學生物件存入Collection集合中

package com.itheima7.ArrayList01;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ArraylestDemo03 {
public static void main(String[] args) {
Collection<Student> st=new ArrayList<>();
st.add(new Student("張三",23,91));
st.add(new Student("李四",25,91));
st.add(new Student("張五",26,93));
st.add(new Student("張三",27,93));
st.add(new Student("張三",28,83));
st.add(new Student("張三",23,87));
st.add(new Student("張三",21,91));
st.add(new Student("張三",23,97));
st.add(new Student("張三",23,82));
st.add(new Student("張三",23,88));
System.out.println(extracted(st));
geimin(st);
fail(st);
}
public static Student extracted(Collection<Student> st) {//構造一個方法,引數型別 Student
Iterator<Student> it = st.iterator(); //建立迭代器
Student st1=null;//給定一個空的Student用於儲存需要返回的st1
int max=0;
while (it.hasNext()){ //判斷下一個是否為空
Student stu = it.next(); //stu儲存當前值 並把指標指向下一個值
if (max< stu.getScore()){//迴圈判斷當前學生分數是否大於max
max=stu.getScore();//大於就賦值給max
st1 =stu; //並且也把值賦給需要返回的st1
}
}
return st1;//Student 內型的返回值st1
}
public static void geimin(Collection<Student> st){
Iterator<Student> it = st.iterator();
int max=0;
while (it.hasNext()){
Student next = it.next();
max+=next.getScore();
}
System.out.println("總分是:"+max+"平均分"+max/10.0);
}
public static void fail(Collection<Student> st){
Iterator<Student> it = st.iterator();
int count=0;
while (it.hasNext()){
Student next = it.next();
if (next.getScore()<60){
count++;
}
}
System.out.println(count);
}

}

class Student{
private String name;
private int age;
private int score;

public Student() {
}

public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}

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 int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}