使用 csv 文件填充二维数组时,我的数组索引超出范围

My array index is out of bounds when populating a 2d array using a csv file

我正在尝试使用 csv 文件填充二维数组,但我一直收到错误提示: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]);

} }

这是我用来填充二维数组的 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

那是因为你说过你的字符串数组的限制是 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] 对于 ,24.89,28.46

...等等

junior[16][0],junior[16][0],junior[16][0] 对于 ,2:20.00,2:35.75

RowC2 当求值超过 16 时会抛出异常。这就是您案例中下一个输入的情况。

您似乎遍历了文件中的每一行。然后你迭代以逗号分隔的字段,并将每个值存储在数组的第二个参数中,然后立即用下一个值覆盖它(不确定你为什么这样做,但我们会继续)。

如果在文件的最后一行之后有一个 new-line,您将尝试插入索引为 17 的行,这是不可能的,因为您只有 17 行,而第一个索引为 0 .

让我们完成最后一行的步骤。

  1. InputLine2 将被设置为空字符串InputLine2 = ""
  2. 下一行的计算结果为 String[] InArray = new String[] { "" };
  3. 最后,您将在 for 循环内设置 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();