创建一个学生类,属性姓名,语文成绩,数学成绩。创建测试类,定义一个集合,从控制台输入四个学生的信息,并将信息存到学生对象中然后添加到集合。对集合按照学生总成绩升序排序,然后遍历数组。分别使用Comparable和Comparator实现。
时间: 2024-03-16 12:41:53 浏览: 79
好的,我可以帮您解答这个问题。以下是您所需的Java代码:
**学生类:**
```java
public class Student {
private String name;
private int chineseScore;
private int mathScore;
public Student(String name, int chineseScore, int mathScore) {
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getTotalScore() {
return chineseScore + mathScore;
}
@Override
public String toString() {
return "姓名:" + name + ",语文成绩:" + chineseScore + ",数学成绩:" + mathScore + ",总成绩:" + getTotalScore();
}
}
```
**测试类:**
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名、语文成绩和数学成绩(用空格分隔):");
String[] info = input.nextLine().split(" ");
String name = info[0];
int chineseScore = Integer.parseInt(info[1]);
int mathScore = Integer.parseInt(info[2]);
Student student = new Student(name, chineseScore, mathScore);
list.add(student);
}
// 使用Comparable排序
Collections.sort(list);
System.out.println("\n使用Comparable排序后的结果:");
for (Student student : list) {
System.out.println(student);
}
// 使用Comparator排序
Collections.sort(list, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getTotalScore() - s2.getTotalScore();
}
});
System.out.println("\n使用Comparator排序后的结果:");
for (Student student : list) {
System.out.println(student);
}
}
}
```
在上面的代码中,我们定义了一个学生类,其中包含了姓名、语文成绩、数学成绩和总成绩等属性。然后,在测试类中,我们创建了一个集合并从控制台输入四个学生的信息,将信息存储到学生对象中并添加到集合中。接着,我们使用Comparable和Comparator分别对集合按照学生总成绩升序排序,并遍历输出结果。
阅读全文