我继续将阵列排除在外,因为学生可以有不同的成绩,因此如果学生没有3年级,但另一个学生没有,我的程序会自动崩溃。我该怎么做才能使该计划根据学生的不同分数。
public class StudentList extends Component{
static ArrayList<Student> studentList = new ArrayList<>();
public static final int ARRAYMAX=4;
public void readStudent()throws Exception{
File window = new File(System.getProperty("user.home"));
JFileChooser choice = new JFileChooser();
choice.setCurrentDirectory(window);
int option = choice.showOpenDialog(this);
File selectedFile = choice.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
File studentFile = new File(selectedFile.getAbsolutePath());
Scanner in = new Scanner(studentFile);
while (in.hasNext()) {
String data = in.nextLine();
String[] studentData = new String[ARRAYMAX];
studentData = data.split("\\|");
for(int i =0; i<ARRAYMAX; i++){
studentData[i] ="0";
}
String firstName = studentData[0];
String lastName = studentData[1];
double grade1 = Double.parseDouble(studentData[2]);
double grade2 = Double.parseDouble(studentData[3]);
double grade3 = Double.parseDouble(studentData[4]);
Student newStudent = new Student(firstName,lastName);
newStudent.setGrades1(grade1);
newStudent.setGrades2(grade2);
newStudent.setGrades3(grade3);
}
}
}
答案 0 :(得分:0)
默认等级(等级1,等级2等)到合理值。在访问studentData并设置成绩之前检查studentData的长度(studentData.length
)。
另一方面,为什么要使用个别grade
字段/ setter?只需将所有等级存储在List或Array字段中,然后根据您的需要访问它。
答案 1 :(得分:0)
好吧,如果我理解正确的话,有些线路没有三年级。如果是这样,您可以检查它是否具有3年级public class StudentList extends Component{ static ArrayList<Student> studentList = new ArrayList<>(); public static final int ARRAYMAX=4; public void readStudent()throws Exception{ File window = new File(System.getProperty("user.home")); JFileChooser choice = new JFileChooser(); choice.setCurrentDirectory(window); int option = choice.showOpenDialog(this); File selectedFile = choice.getSelectedFile(); if (option == JFileChooser.APPROVE_OPTION) { System.out.println("Selected file: " + selectedFile.getAbsolutePath()); } File studentFile = new File(selectedFile.getAbsolutePath()); Scanner in = new Scanner(studentFile); while (in.hasNext()) { String data = in.nextLine(); String[] studentData = new String[ARRAYMAX]; studentData = data.split("\\|"); for(int i =0; i<ARRAYMAX; i++){ studentData[i] ="0"; } String firstName = studentData[0]; String lastName = studentData[1]; double grade1 = Double.parseDouble(studentData[2]==null?"0":studentData[2]); double grade2 = Double.parseDouble(studentData[3]==null?"0":studentData[3]); double grade3 = Double.parseDouble(studentData[4]==null?"0":studentData[4] ); Student newStudent = new Student(firstName,lastName); newStudent.setGrades1(grade1); newStudent.setGrades2(grade2); newStudent.setGrades3(grade3); } }