有五个学生,每个学生有3门课的成绩 从键盘输入以上数据(包括姓名,三门课成绩) 输入的格式:如:zhangsan,30,40,50计算出总成绩 并把学生的信息和计算出的总分数从高到底顺序存放在磁盘文件“Stud.txt”中运用javaooppoi流完成
时间: 2024-10-11 13:16:34 浏览: 24
为了实现这个需求,你可以按照以下步骤使用Java、OOP(面向对象编程)以及Apache POI库来处理数据并将其保存到磁盘文件:
1. 首先,需要创建一个`Student`类,用于存储学生的姓名和课程成绩信息:
```java
public class Student {
private String name;
private int score1;
private int score2;
private int score3;
// 构造函数
public Student(String name, int score1, int score2, int score3) {
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
// 计算总成绩
public int getTotalScore() {
return score1 + score2 + score3;
}
// 获取方法
// ... (getter and setter methods)
}
```
2. 创建一个主类来获取用户输入,创建学生对象,并排序:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
if (data.length == 4) {
String name = data[0];
int score1 = Integer.parseInt(data[1]);
int score2 = Integer.parseInt(data[2]);
int score3 = Integer.parseInt(data[3]);
students.add(new Student(name, score1, score2, score3));
}
}
// 关闭扫描器
scanner.close();
// 按总分降序排序
Collections.sort(students, (a, b) -> b.getTotalScore() - a.getTotalScore());
// 写入Excel文件
try (Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Students")) {
// ... (write student information to the Excel file using row and cell operations)
// 将排序后的学生列表写入文件
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
writeRowToSheet(sheet, i + 1, student);
}
// Save the file
File file = new File("Stud.txt");
workbook.write(file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Write student details to a specific row in the sheet
private static void writeRowToSheet(Sheet sheet, int rowNum, Student student) {
// ... (implement the logic to create a row with student's name and total score)
}
}
```
3. 完成`writeRowToSheet`方法,将学生信息写入到Excel的特定行:
```java
private static void writeRowToSheet(Sheet sheet, int rowNum, Student student) {
Row row = sheet.createRow(rowNum);
Cell nameCell = row.createCell(0);
nameCell.setCellValue(student.getName());
Cell totalScoreCell = row.createCell(1);
totalScoreCell.setCellValue(student.getTotalScore());
// You may also add formatting or conditional formatting here if needed.
}
```
当运行此程序时,它会提示用户输入学生信息,然后计算总成绩并按总分从高到低排序,最后将结果保存到名为"Stud.txt"的Excel文件中。
阅读全文