2015-04-25 43 views
0

嘗試從String解析爲Integerdouble時出現錯誤。解析爲整數時出現索引超出範圍錯誤

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; 
} 

它產生錯誤:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

謝謝

+2

Integer.parseInt不應該拋出一個ArrayIndexOutOfBoundsException,它只能來自一個數組! stacktrace會很有用 – Distjubo

+0

分享更多代碼 – sparsh610

+1

'學生'的長度是多少? 'student.length'和'lineText'可能會有所不同... – Radiodef

回答

0

索引越界意味着

stringParts[2] 

做不存在。檢查數組的長度。分裂大概isent正如你所期望的那樣工作