Java 解析为整数时出现索引越界错误

Java 解析为整数时出现索引越界错误,java,parsing,indexoutofboundsexception,Java,Parsing,Indexoutofboundsexception,尝试将字符串解析为整数或双精度时出错 int id = Integer.parseInt(stringParts[2]); 如果我打印stringParts[2]它可以工作,它只会在解析时抛出一个错误 这是我使用的完整循环: public static StudentRecord[] creates(String fileName) throws IOException { BufferedReader br = new BufferedReader(new FileReader(

尝试将
字符串
解析为
整数
双精度
时出错

int id = Integer.parseInt(stringParts[2]);
如果我打印
stringParts[2]
它可以工作,它只会在解析时抛出一个错误

这是我使用的完整循环:

  public static StudentRecord[] creates(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("/Users/DNA40/Desktop/lab11input.txt"));
    int lineText = lineCount("/Users/DNA40/Desktop/lab11input.txt");
    String record;
    String cons = ("[ ]");

    StudentRecord[] student = new StudentRecord[lineText]; 

    String[] stringParts = new String[5];
    for(int i = 0; i < lineText ; i++){


        student[i] = new StudentRecord();//Creates Object class
        record = br.readLine(); //Stores the first line of text file

        stringParts = record.split("\\s+");//Splits the line into parts
        student[i].setFirstName(stringParts[0]);
        student[i].setLastName(stringParts[1]);
        int id = Integer.parseInt(stringParts[2]);
        student[i].setID(id);
        double gpa = Double.parseDouble(stringParts[3]);
        student[i].setGPA(gpa);
        int hours = Integer.parseInt(stringParts[4]);
        student[i].setHours(hours);


        }


        return student;
    }






public static int lineCount(String fileName) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(fileName));
    int count = 0;
    String currentLine;



    while ((currentLine = br.readLine()) != null){
        count++;

    }



    return count;
}
publicstaticstudentrecord[]创建(字符串文件名)引发IOException{
BufferedReader br=新的BufferedReader(新的文件阅读器(“/Users/DNA40/Desktop/lab11input.txt”);
int lineText=lineCount(“/Users/DNA40/Desktop/lab11input.txt”);
字符串记录;
字符串cons=(“[]”);
StudentRecord[]学生=新StudentRecord[lineText];
字符串[]stringParts=新字符串[5];
对于(int i=0;i
它在线程“main”java.lang.ArrayIndexOutOfBoundsException中生成错误:
异常:2


谢谢

索引越界意味着

stringParts[2]

不存在。检查数组的长度。拆分可能未按您预期的那样工作。parseInt不应抛出ArrayIndexOutOfBoundsException,该异常只能来自数组!stacktrace很有用学生的长度是多少<代码>学生。长度
行文本
可能不同…什么是行文本?在循环过程中它的价值是什么?我添加了更多的代码。lineText是文本文件中的行数,即两行。不要相信这是实际代码,因为这一行运行得非常好。