【发布时间】:2017-08-30 08:21:58
【问题描述】:
我继续让数组越界,因为学生可能有不同数量的成绩,因此,如果一个学生没有 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);
}
}
}
【问题讨论】:
-
studentData 的长度等于 ARRAYMAX,即 4,但您正在尝试访问 studentData[4],它是数组中的第 5 个索引。这不起作用,您必须将 ARRAYMAX 更改为 5 才能访问索引 4。数组索引为 0。
标签: java io inputstream jfilechooser