java-list

java-list

某中学有若干学生学生对象放在一个List中,每个学生有一个姓名属性、班级名称属性(String)和考试成绩属性(int),某次考试结束后,每个学生都获得了一个考试成绩。请打印出每个班级的总分和平均分。

源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.practice3;
/***
* 自定义CompareTo接口
* @author HDC
*/
public interface MyCompare<T> {
int myCompareTo(T o);
}
package com.practice3;
/***
* 自定义MySort排序
*/
import java.util.List;
public class MySort {
public static <T extends MyCompare<T>> void sort(List<T> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if ((list.get(i)).myCompareTo(list.get(j))>0) {
T t = list.get(i);
list.set(i, list.get(j));
list.set(j, t);
}
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.practice3;
/***
* 学生类里面有班级,姓名,成绩属性
* @author HDC
*
*/
public class Student implements MyCompare<Student>{
private String name;
private String cls;
private int grade;
public Student(String name,String cls,int grade){
this.name=name;
this.cls=cls;
this.grade=grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCls() {
return cls;
}
public void setCls(String cls) {
this.cls = cls;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public int myCompareTo(Student o) {
if(o.cls.compareTo(this.cls)!=0){
return o.cls.compareTo(this.cls);
}else if(o.name.compareTo(this.name)!=0){
return o.name.compareTo(this.name);
}else{
return this.grade-o.grade;
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.practice3;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/***
* 测试学生类
* @author HDC
*/
public class Test {
public static void main(String[] args) {
List<Student> std = new ArrayList<Student>();
std.add(new Student("asd", "A", 80));
std.add(new Student("qwe", "C", 70));
std.add(new Student("zxc", "B", 60));
std.add(new Student("aaa", "A", 70));
std.add(new Student("sss", "C", 90));
std.add(new Student("ddd", "C", 85));
std.add(new Student("dfd", "B", 70));
std.add(new Student("dfg", "A", 90));
MySort.sort(std);
for (Student s : std) {
System.out.println(s.getCls()+"\t"+s.getName()+"\t"+s.getGrade());
}
System.out.println("---------------------------");
//求平均分和总分
Iterator<Student> it = std.iterator();// 使用迭代器
Student s = it.next();// 获取对象
String cls = s.getCls();
int sum=s.getGrade(),i=1;
while (it.hasNext()) {// 判断迭代器当中是否存在下一个数
s = it.next();// 获取对象
if(s.getCls()!=cls){
System.out.println(cls+"班的总分为:"+sum+"\t平均分是:"+(double)sum/i);
cls=s.getCls();
i=1;
sum=s.getGrade();
}else{
i++;
sum+=s.getGrade();
}
}
System.out.println(cls+"班的总分为:"+sum+"\t平均分是:"+(double)sum/i);
}
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!