猿问

我的代码收到 ArrayIndexOutOfBoundsException。这个设置正确吗?

我正在使用一个 .txt 文件,其中的数据格式始终相同。

例如:

  • 标题|格式|onLoan|loanedTo|loanedOn

  • 标题|格式|onLoan|loanedTo|loanedOn

  • 标题|格式|onLoan|loanedTo|loanedOn

  • 标题|格式|onLoan|loanedTo|loanedOn

我正在打开文件,然后尝试将该信息传输到类对象中,然后将该对象放入该类的 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。


POPMUISE
浏览 109回答 2
2回答

狐的传说

确保列没有任何缺失值。还要检查空的新行。

素胚勾勒不出你

看起来有些行不遵循描述的格式。我的建议 - 在数组处理之前添加条件&nbsp; &nbsp; ...&nbsp; &nbsp; libraryItem = mediaItemString.split("\\|");&nbsp; &nbsp; if(libraryItem.length <5) {&nbsp; &nbsp; &nbsp; &nbsp; log.error("Error: libraryItem.length is {} for string {}", libraryItem.length, mediaItemString);&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(libraryItem[0].toString());&nbsp; &nbsp; ...
随时随地看视频慕课网APP

相关分类

Java
我要回答