为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

POPMUISE 2022-11-02 10:49:00
我正在使用一个 .txt 文件,其中的数据格式始终相同。例如:标题|格式|onLoan|loanedTo|loanedOn标题|格式|onLoan|loanedTo|loanedOn标题|格式|onLoan|loanedTo|loanedOn标题|格式|onLoan|loanedTo|loanedOn我正在打开文件,然后尝试将该信息传输到类对象中,然后将该对象放入该类的 arrayList 中。我遇到的问题是古老的 ArrayIndexOutOfBoundsException。我不确定是什么原因造成的。这可能很简单。任何指导将不胜感激。java.lang.ArrayIndexOutOfBoundsException: 1at Library.open(Library.java:230)Scanner input = null;String mediaItemString = "";MediaItem open = new MediaItem();  //class created for this objectString[] libraryItem;  //try catch block for exception handlingtry {    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。
查看完整描述

2 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

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



查看完整回答
反对 回复 2022-11-02
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

看起来有些行不遵循描述的格式。


我的建议 - 在数组处理之前添加条件


    ...

    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());

    ...


查看完整回答
反对 回复 2022-11-02
  • 2 回答
  • 0 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号