[英]I am getting an ArrayIndexOutOfBoundsException with my code. Is this setup correctly?
I am using a .txt file that has data in it formatted the same way throughout.我正在使用一个 .txt 文件,其中的数据格式始终相同。
For example:例如:
I am opening the file and then trying to transfer that information into class object and then put that object in a arrayList of that class.我正在打开文件,然后尝试将该信息传输到类对象中,然后将该对象放入该类的 arrayList 中。
The problem I am having is with the age old ArrayIndexOutOfBoundsException.我遇到的问题是古老的 ArrayIndexOutOfBoundsException。 I am not sure what is causing it.我不确定是什么原因造成的。 It is probably something simple.这可能很简单。 Any guidance would be appreciated.任何指导将不胜感激。
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();
}
Well I was hoping to split the string with delimiters and then assign those values to the MediaItem appropriately.好吧,我希望用分隔符分割字符串,然后将这些值适当地分配给 MediaItem。
It looks like some lines does not follow described format.看起来有些行不遵循描述的格式。
My suggection - add condition before array processing like我的建议 - 在数组处理之前添加条件,例如
...
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());
...
Make sure you don't have any missing value for a column.确保列没有任何缺失值。 Also check for empty new lines.还要检查空的新行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.