java需求:键盘录入3个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高 到低输出到控制台
时间: 2024-01-09 10:06:03 浏览: 173
JAVA 键盘录入学生成绩,排序后输出
好的,请按照以下步骤进行操作:
1. 创建一个名为`Student`的Java类,该类包含学生的姓名和各科成绩。具体代码如下:
```java
public class Student {
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student(String name, int chineseScore, int mathScore, int englishScore) {
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public int getTotalScore() {
return chineseScore + mathScore + englishScore;
}
}
```
2. 在主类中,使用`Scanner`类从键盘录入学生信息,并将学生放入一个列表中。然后按照总分从高到低排序并输出到控制台。具体代码如下:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名:");
String name = scanner.nextLine();
System.out.println("请输入第" + (i + 1) + "个学生的语文成绩:");
int chineseScore = scanner.nextInt();
System.out.println("请输入第" + (i + 1) + "个学生的数学成绩:");
int mathScore = scanner.nextInt();
System.out.println("请输入第" + (i + 1) + "个学生的英语成绩:");
int englishScore = scanner.nextInt();
scanner.nextLine(); // 读取换行符
Student student = new Student(name, chineseScore, mathScore, englishScore);
students.add(student);
}
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getTotalScore() - s1.getTotalScore();
}
});
System.out.println("按总分从高到低排序的学生信息如下:");
for (Student student : students) {
System.out.println("姓名:" + student.getName() + ",总分:" + student.getTotalScore());
}
}
}
```
以上代码实现了键盘录入3个学生信息,并按照总分从高到低输出到控制台。你可以根据需求进行适当的修改。
阅读全文