[英]My array index is out of bounds when populating a 2d array using a csv file
我正在尝试使用csv文件填充2D数组,但我不断收到错误消息:ArrayIndexOutOfBoundsException:17.问题似乎在“ for”中,但我在理解原因时遇到了麻烦。 感谢您的帮助,在此先感谢您!
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public String[][] junior = new String[17][1];
public CSVRead() throws IOException {
{
Scanner scanner = null;
int Rowc2=0;
String InputLine2 = "";
String xfilelocation2;
xfilelocation2 = ("//Users//Pdubru//Downloads//arrays.csv");
scanner = new Scanner (new BufferedReader (new FileReader (xfilelocation2)));
while (scanner.hasNextLine()){
InputLine2 = scanner.nextLine();
String[] InArray = InputLine2.split (",");
for (int x=0; x< InArray.length; x++){
junior [Rowc2][0] = InArray[x];
}
Rowc2++;
}
} //main()
System.out.println(junior [1][0]);
}}
这是我用来填充2D数组的CSV文件:
,MALE,FEMALE
,24.89,28.46
,55.05,1:02.78
,2:02.46,2:17.08
,4:23.01,4:49.58
,9:09.20,9:58.57
,17:35.59,19:10.28
,26.87,30.94
,1:00.81,1:08.89
,2:17.67,2:34.18
,29.09,32.23
,1:03.00,1:11.02
,2:19.78,2:33.72
,31.56,37.1
,1:10.62,1:21.23
,2:36.40,2:54.79
,2:20.00,2:35.75
,4:59.87,5:35.37
那是因为您说过String数组的限制为17-
public String[][] junior = new String[17][1];
但最终您的代码
while (scanner.hasNextLine()){
InputLine2 = scanner.nextLine();
String[] InArray = InputLine2.split (",");
for (int x=0; x< InArray.length; x++){
junior [Rowc2][0] = InArray[x]; // even this isn't useful (why explained further below)
}
Rowc2++; // this causes the Exception
}
当您按照以下模式存储值时-
junior[0][0],junior[0][0],junior[0][0]
,MALE,FEMALE
junior[1][0],junior[1][0],junior[1][0]
for ,24.89,28.46
... 等等
junior[16][0],junior[16][0],junior[16][0]
for ,2:20.00,2:35.75
当RowC2
值超过16时,将引发异常。 这就是您的情况下下一个输入所发生的情况。
看起来您遍历文件中的每一行。 然后,您要遍历用逗号分隔的字段,并将每个值存储在数组的第二个参数中,然后立即用下一个值覆盖它(不知道为什么这样做,但我们继续)。
如果文件的最后一行之后有换行,则您将尝试插入索引为17的行,这是不可能的,因为您只有17行,并且第一个索引为0。
让我们逐步完成最后一行的步骤。
InputLine2 = ""
String[] InArray = new String[] { "" };
junior [17][0] = ""
; 这将看到上面的异常。
您可能应该使用列表,而不是数组,那么文件的长度无关紧要。
为什么不这样:
Scanner scanner = ....
Iterable<String> iterable = () -> scanner; // convert to iterable
Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
String[][] data = stream.filter(s -> s != null && s.contains(","))
.map(s -> new String[] { s.substring(s.lastIndexOf(",")+1) })
.toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.