Java输入学生姓名,Java成绩,按分数从高到低排序后存储在文件score.txt中。
时间: 2024-02-15 09:05:09 浏览: 156
student-Score--java.zip_Score!
好的,这个问题可以分为以下几个步骤:
1. 创建一个存储学生信息的类,包括学生姓名和Java成绩两个属性。
```java
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
2. 读取用户输入的学生姓名和Java成绩,并将其封装为一个Student对象,然后将所有的Student对象存储在一个List中。
```java
List<Student> students = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入学生姓名和Java成绩,以空格分隔(输入exit退出):");
String input = scanner.nextLine();
if ("exit".equals(input)) {
break;
}
String[] parts = input.split(" ");
String name = parts[0];
int score = Integer.parseInt(parts[1]);
students.add(new Student(name, score));
}
```
3. 对List中的学生信息按照Java成绩从高到低进行排序。
```java
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getScore() - s1.getScore();
}
});
```
4. 将排序后的学生信息写入文件score.txt中。
```java
try (PrintWriter writer = new PrintWriter("score.txt")) {
for (Student student : students) {
writer.println(student.getName() + " " + student.getScore());
}
} catch (IOException e) {
e.printStackTrace();
}
```
完整代码如下:
```java
import java.io.IOException;
import java.io.PrintWriter;
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);
while (true) {
System.out.println("请输入学生姓名和Java成绩,以空格分隔(输入exit退出):");
String input = scanner.nextLine();
if ("exit".equals(input)) {
break;
}
String[] parts = input.split(" ");
String name = parts[0];
int score = Integer.parseInt(parts[1]);
students.add(new Student(name, score));
}
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getScore() - s1.getScore();
}
});
try (PrintWriter writer = new PrintWriter("score.txt")) {
for (Student student : students) {
writer.println(student.getName() + " " + student.getScore());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
阅读全文