第一步、先创建一个学生类对象,再重写toString方法
Student类:
public class Student {
private String name;
private double chinese;
private double math;
private double english;
public Student(String name, double chinese, double math, double english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getChinese() {
return chinese;
}
public void setChinese(double chinese) {
this.chinese = chinese;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
}
测试类:
import day15_8_13.studentGradePaiXu.Student;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class StudentGrade {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
//创建一个学生对象数组
Student[] students = new Student[5];
for(int i=0;i<5;i++){
System.out.println("请按指定格式输入:姓名,语文成绩,数学成绩,英语成绩");
String s=sc.next();
String[] split = s.split(",");
students[i]=new Student(split[0],Double.parseDouble(split[1]),Double.parseDouble(split[2]),Double.parseDouble(split[3]));
}//遍历数组,再按照总分排序
for(int i=0;i<students.length;i++){
for(int j=i+1;j<students.length;j++){
if((students[i].getChinese()+students[i].getMath()+students[i].getEnglish())>(students[j].getChinese()+students[j].getMath()+students[j].getEnglish())){
Student stu=students[i];
students[i]=students[j];//数组能进行遍历排序
students[j]=stu;
}
}
}
//排序完后,直接遍历数组的同时将内容写到笔记本中
BufferedWriter bw = new BufferedWriter(new FileWriter("src/main/java/day15_8_13/haha/zuoye/a.txt"));
for (Student student : students) {
bw.write("总分为:"+(student.getChinese()+student.getMath()+student.getEnglish())+student);
bw.newLine();
}
//释放资源
bw.close();
}
}
创建一个学生对象的数组,更加方便的将每次录入的信息直接存储在对象数组里,避免了多次重复写new Student()来接收。
标签:name,chinese,double,文本文件,Student,高到,成绩,public,math From: https://blog.csdn.net/ABU009/article/details/141286204