使用java语言将键盘输入的学生信息(包括学号、姓名和成绩)逐行写入文件Student.dat,当输入exit时结束。 统计文件Student.dat中包含的学生数,以及平均分、最高分和最低分。 程序检查成绩输入值,如果不是数值信息,或是负的数值信息,或超过成绩范围(100),抛出相应的异常。在抛出异常之前应提供详细的信息说明,从而使使用该程序的用户了解所出现的问题,同时考虑上述异常出现时程序应该如何处理。
时间: 2024-03-21 10:39:52 浏览: 21
好的,这是一个关于Java文件读写和异常处理的问题。可以通过以下代码实现:
```
import java.io.*;
import java.util.ArrayList;
class Student{
private int id;
private String name;
private int score;
public Student(int id, String name, int score){
this.id = id;
this.name = name;
this.score = score;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
}
public class StudentManager{
public static void main(String[] args){
ArrayList<Student> students = new ArrayList<Student>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
try{
FileWriter fw = new FileWriter("Student.dat");
while((line = br.readLine()) != null && !line.equals("exit")){
String[] info = line.split("\\s+");
int id = Integer.parseInt(info[0]);
String name = info[1];
int score = Integer.parseInt(info[2]);
if(score < 0 || score > 100){
throw new Exception("成绩输入值不合法!");
}
students.add(new Student(id, name, score));
fw.write(line + "\n");
}
fw.close();
}catch(IOException e){
System.out.println("文件写入错误!");
e.printStackTrace();
}catch(Exception e){
System.out.println(e.getMessage());
}
//统计信息
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(Student s : students){
sum += s.getScore();
if(s.getScore() > max){
max = s.getScore();
}
if(s.getScore() < min){
min = s.getScore();
}
}
System.out.println("学生数:" + students.size());
System.out.println("平均分:" + (double)sum / students.size());
System.out.println("最高分:" + max);
System.out.println("最低分:" + min);
}
}
```
程序首先创建了一个Student类来存储学生信息,然后通过BufferedReader从控制台读取学生信息,将其写入Student.dat文件中。在读取每个学生信息时,程序会检查成绩输入值是否合法,若不合法,则抛出异常并输出错误信息。最后程序会统计文件中包含的学生数,以及平均分、最高分和最低分。
希望这个代码能够帮到你!