[英]Getting an ArrayIndexOutOfBoundsException: 2 When I use different delimiters for splitting strings
I'm getting an ArrayIndexOutOfBoundsException: 2 and have no idea how to fix it. 我收到ArrayIndexOutOfBoundsException:2,不知道如何解决。 It happened when I change my delimiter from (",") to ("^[A-Za-z]+). Here is the method I'm having the problem in:
当我将定界符从(“,”)更改为(“ ^ [A-Za-z] +)时,发生了这种情况,这是我遇到问题的方法:
public void populateArrayList() throws FileNotFoundException{
File inputFile = new File("StirlingHistoric.csv");
Scanner scan = new Scanner(inputFile);
while(scan.hasNext()){
String line = scan.next();
String [] input = line.split("^[A-Za-z]+"); // try get the useDelimiter method to work instead
addEntry(input[0], input[1], input[2], input[3], input[4], input[5]);
}
scan.close();
}
The program crashes at the call to addEntry. 程序在调用addEntry时崩溃。 The thing is if I use the:
事情是,如果我使用:
String [] input = line.split(",");
as delimiter it works fine but there is still other symbols in the .csv file I have to get rid of, mostly just quotation marks, so it made sense to use the ("^[A-Za-z]+")
delimiter. 作为定界符,它可以正常工作,但.csv文件中还有其他一些我必须要删除的符号,大部分只是引号,因此使用
("^[A-Za-z]+")
定界符是有意义的。
I have uploaded two images of my debugger that gives some information of whats happening in the array. 我上传了调试器的两个图像,这些图像提供了阵列中发生的情况的一些信息。 I have highlighted (in the images) some lines of code in green and blue to draw attention to them.
我已在图中突出显示了一些绿色和蓝色的代码行,以引起人们的注意。 And have also made some comments on the images.
并且还对图像做了一些评论。 Here is the links:
这里是链接:
Pic 1: http://tinypic.com/r/25hdbgx/8 图片1: http : //tinypic.com/r/25hdbgx/8
Pic 2: http://tinypic.com/r/35lb3nt/8 图片2: http : //tinypic.com/r/35lb3nt/8
Just click on the image to enlarge it. 只需单击图像即可放大。 If you would like me to post the entire class this method belongs to just let me know.
如果您想让我发布整个类,请告诉我。 Thanks
谢谢
Put the ^
inside the []
to match a chararcter except. 将
^
放在[]
以匹配字符,除了。
"[^A-Za-z]+"
A ^
outside matches the beginning of the input. 外部的
^
匹配输入的开头。
Also, test the size of the resulting array: 另外,测试结果数组的大小:
if(input.length < 5 ) /* do something */;
edit: 编辑:
How do you know when the code hits addEntry
if there even is a input[5]
? 您如何知道即使有
input[5]
时候代码addEntry
击中addEntry
? Or is that a constant factor in the file? 还是文件中的常数? You know for sure that when you split the input string there will only be arrays of 6 elements and not smaller?
您确定要分割输入字符串时,只有6个元素的数组,而不是更小的数组吗? Because if thats the case then it explains the arrayindexoutofbounds exception on that line.
因为如果是这种情况,那么它将解释该行上的arrayindexoutofbounds异常。
A solution to that would be to pass the input array as a parameter in the addEntry method and deal with different lengths there. 一种解决方法是将输入数组作为addEntry方法中的参数传递,并在那里处理不同的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.