JAVA-将字符串拆分为令牌,但失败并出现错误

时间:2017-05-25 23:52:14

标签: java arrays token

我试图从一个包含20行的文本文件中读取并将它们存储到一个数组中并为它们分配一个变量firstname lastname和grade。因为我必须输出它们作为姓氏,名字和等级,我决定使用令牌但不知何故我得到这个错误:java.lang.ArrayIndexOutOfBoundsException:1

public static void main(String[] args) throws IOException {
    int numberOfLines = 20; 
    studentClass[] studentObject = new studentClass[numberOfLines];
    readStudentData(studentObject);

}    
    public static void readStudentData(studentClass[] studentObject)throws  {

    //create FileReader and BufferedReader to read and store data
    FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
    BufferedReader br = new BufferedReader (fr);


    String line = null;
    int i = 0;

    //create array to store data for firstname, lastname, and score
    while ((line = br.readLine()) != null){
       String[] stuArray = line.split(" ");
       String stuFName = stuArray[0];
       String stuLName = stuArray[1];
       int score = Integer.parseInt(stuArray[2]);
       studentObject[i] = new studentClass (stuFName, stuLName, score);
       i++;
    }
    br.close();
    for(i = 0; i<studentObject.length; i++){
        System.out.print(studentObject[i].getStudentFName());
    }

}

我得到的错误特别是这一行:

String stuLName = stuArray[1];

这是文本文件:

Duckey Donald 85
Goof Goofy 89
Brave Balto 93
Snow Smitn 93
Alice Wonderful 89
Samina Akthar 85
Simba Green 95
Donald Egger 90
Brown Deer 86
Johny Jackson 95
Greg Gupta 75
Samuel Happy 80
Danny Arora 80
Sleepy June 70
Amy Cheng 83
Shelly Malik 95
Chelsea Tomek 95
Angela Clodfelter 95
Allison Nields 95
Lance Norman 88

2 个答案:

答案 0 :(得分:0)

我认为在你文件的最后一行你有空格。确保最后一行没有空格或制表符等空白区域。

答案 1 :(得分:0)

首先,下次您还应在代码中包含导入和输出 为了让我们能够轻松修复它,还有一件事,类名应该是 S tudentClass,而不是 s tudentClass,它与我的方法不同。 其次,我不能在没有你的studentClass的情况下测试你的代码......所以我只能猜到它:      考虑1:文本文件还有一行(带空格)&gt;&gt;不可能,因为String test = " "; test.split(" ")[0] == null;      考虑2:您的文本文件有错误,要测试它,我建议您添加 System.out.println(line + ".")之后while ((line = br.readLine()) != null){ 为了测试它,请相信我,你会得到最后一行,因为它会膨胀;

相关问题