Java 我正在使用代码获取ArrayIndexOutOfBoundsException。这个设置正确吗?

Java 我正在使用代码获取ArrayIndexOutOfBoundsException。这个设置正确吗?,java,file,exception,indexoutofboundsexception,Java,File,Exception,Indexoutofboundsexception,我使用的是一个.txt文件,其中的数据格式与整个文件相同 例如: 标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 我打开文件,然后尝试将该信息传输到类对象中,然后将该对象放入该类的arrayList中 我遇到的问题是关于古老的ArrayIndexOutOfBoundsException。我不确定是什么原因造成的。这可能很简单。任何指导都将不胜感激 java.lang.ArrayIndexOutOfBoundsExceptio

我使用的是一个.txt文件,其中的数据格式与整个文件相同

例如:

标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 标题|格式|唯一|借出|借出 我打开文件,然后尝试将该信息传输到类对象中,然后将该对象放入该类的arrayList中

我遇到的问题是关于古老的ArrayIndexOutOfBoundsException。我不确定是什么原因造成的。这可能很简单。任何指导都将不胜感激

java.lang.ArrayIndexOutOfBoundsException: 1
at Library.open(Library.java:230)


Scanner input = null;
String mediaItemString = "";
MediaItem open = new MediaItem();  //class created for this object
String[] libraryItem;  
//try catch block for exception handling
try {
    input = new Scanner(new File("library.txt"));           
    while (input.hasNextLine()) {
        mediaItemString = input.nextLine();
        libraryItem = mediaItemString.split("\\|");
        System.out.println(libraryItem[0].toString());
        System.out.println(libraryItem[1].toString());  //error here, line 230               
        System.out.println(Boolean.parseBoolean(libraryItem[2].toString()));
        System.out.println(libraryItem[3].toString());
        System.out.println(libraryItem[4].toString());
        open.setTitle(libraryItem[0].toString());
        open.setFormat(libraryItem[1].toString());               
        open.setOnLoan(Boolean.parseBoolean(libraryItem[2].toString()));
        open.setLoanedTo(libraryItem[3].toString());
        open.setDateLoaned(libraryItem[4].toString());
        items.add(open);
    }
} catch (FileNotFoundException e){
    System.out.println("There was an error with the file.");
} finally {
    input.close();
}

我希望用分隔符分割字符串,然后将这些值适当地分配给MediaItem。

看起来有些行不符合所描述的格式

My SuggeAction-在数组处理之前添加条件,如

    ...
    libraryItem = mediaItemString.split("\\|");
    if(libraryItem.length <5) {
        log.error("Error: libraryItem.length is {} for string {}", libraryItem.length, mediaItemString);
        continue;
    }
    System.out.println(libraryItem[0].toString());
    ...

确保列中没有任何缺少的值。还要检查是否有空行。

文件中是否有空行?您是否尝试过在引发异常时调试mediaItemString的值?您需要学习应用基本调试技术。即使不使用比您想象的更简单的调试器,也只需在访问其元素之前打印字符串和数组,您就会知道问题所在。有一条额外的线。我进入文件,删除了这一行,它工作了。经过进一步的调查…当我写文件时,我加入了一个换行符。我完全忽略了检查mediaItemString。其他println输出用于调试。再次感谢。很高兴你发现了。希望您喜欢自己发现问题的感觉:-