线程 "main" java.lang.ArrayIndexOutOfBoundsException 中的异常:尝试访问数组元素时出现 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 when trying to access element of Array
我正在编写一个程序,将学生的姓名、学号和他的课程成绩存储在文本文件中。
现在正在写获取学生成绩的方法。该方法获取所需的学号作为输入。在下面的代码中我得到了错误
java.lang.ArrayIndexOutOfBoundsException
,对于行:
System.out.println(studentFile [1]);
和 if 语句.
我想我访问元素的方式不对,但我不是 100% 确定。其余的方法工作起来轻而易举。
public static void getGradeOfStudentNumber(String studentNumberForGrade){
try
{
String line;
BufferedReader br = new BufferedReader(new
FileReader("StudentArchive.txt"));
while((line = br.readLine())!= null)
{
String[] studentFile = line.split(",");
System.out.println(Arrays.toString(studentFile));
System.out.println(studentFile [1]);
/*if ((studentFile[1]).equals(studentNumberForGrade))
{
String grade = studentFile[2];
System.out.println("the student's grade is "+ grade);
}*/
}
br.close();
}
catch (IOException ex)
{
System.out.println("The file does not exist");
}
}
}
在从 array
检索数据之前检查数组的 length more than 2
是否:
if(studentFile.length>=2)
System.out.println(studentFile[1]);
我正在编写一个程序,将学生的姓名、学号和他的课程成绩存储在文本文件中。
现在正在写获取学生成绩的方法。该方法获取所需的学号作为输入。在下面的代码中我得到了错误
java.lang.ArrayIndexOutOfBoundsException
,对于行:
System.out.println(studentFile [1]);
和 if 语句.
我想我访问元素的方式不对,但我不是 100% 确定。其余的方法工作起来轻而易举。
public static void getGradeOfStudentNumber(String studentNumberForGrade){
try
{
String line;
BufferedReader br = new BufferedReader(new
FileReader("StudentArchive.txt"));
while((line = br.readLine())!= null)
{
String[] studentFile = line.split(",");
System.out.println(Arrays.toString(studentFile));
System.out.println(studentFile [1]);
/*if ((studentFile[1]).equals(studentNumberForGrade))
{
String grade = studentFile[2];
System.out.println("the student's grade is "+ grade);
}*/
}
br.close();
}
catch (IOException ex)
{
System.out.println("The file does not exist");
}
}
}
在从 array
检索数据之前检查数组的 length more than 2
是否:
if(studentFile.length>=2)
System.out.println(studentFile[1]);