题目:
请编写程序,完成键盘录入学生信息,并计算总分将学生信息与总分一同写入文本文件.
要求键盘录入3个学生信息(姓名,语文成绩,数学成绩) 求出每个学生的总分 ,并且将学生的信息写入Student.txt文件中.
文件中的效果下所示:
姓名 语文成绩 数学成绩 总分
李四 99 88 177
张三 20 90 112
王五 100 100 200
答案:
自定义一个异常类来处理用户输入成绩不合规的情况.加强程序健壮性.
//类名要见名知意,长一点没关系
public class IllegalScoreException extends RuntimeException{
public IllegalScoreException() {
}
public IllegalScoreException(String message) {
super(message);
}
}
创建Student学生类封装学生信息
@Data
public class Student {
private String name;
private int chineseScore;
private int mathScore;
private int totalScore;
public Student(String name, int chineseScore, int mathScore) {
if (chineseScore>100 || chineseScore<0) throw new IllegalScoreException("分数不合法");
if (mathScore>100 || mathScore<0) throw new IllegalScoreException("分数不合法");
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.totalScore = chineseScore+mathScore;
}
}
实现题目要求
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.*in*);
System.*out*.println("请录入学生信息:");
System.*out*.println("录入格式 : 姓名 语文成绩 数学成绩");
try (FileOutputStream os = new FileOutputStream("Student.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);) {
bos.write("姓名\t语文成绩\t数学成绩\t总成绩\r".getBytes());
bos.flush();
//已知循环次数,用for循环
for (int i = 0; i < 3; i++) {
System.*out*.println("请输入第" + (i + 1) + "个学生信息:");
String s = scanner.nextLine();
String[] split = s.split("\\ +");
Student student = new Student(split[0], Integer.*parseInt*(split[1]), Integer.*parseInt*(split[2]));
bos.write((student.getName() + "\t" + student.getChineseScore() + "\t\t" + student.getMathScore() + "\t\t" + student.getTotalScore() + "\r").getBytes());
bos.flush();
}
}catch(IllegalScoreException|NumberFormatException|ArrayIndexOutOfBoundsException e){
System.*out*.println("分数不合法,请确认后输入");
}
catch (Exception e) {
e.printStackTrace();
System.*out*.println("录入失败,请重试");
}
这里的四个异常的作用要能够理解明白.
结果显示: