线程 "main" java.lang.ArrayIndexOutOfBoundsException 中的异常:正确索引数组的 7

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 for correctly indexed array

我有一个包含 8 列的 CSV 文件:

我已经使用以下代码将每一列放入一个数组中

public static void main(String args[]) {

    List<String> wholefile = new ArrayList<String>();
    List<String> id = new ArrayList<String>();
    List<String> property_address = new ArrayList<String>();
    List<String> first_name = new ArrayList<String>();
    List<String> last_name = new ArrayList<String>();
    List<String> email = new ArrayList<String>();
    List<String> owner_address = new ArrayList<String>();
    List<String> price = new ArrayList<String>();
    List<String> date_sold = new ArrayList<String>();


    Path filepath = Paths.get("./data.csv");


    try {

      BufferedReader br = new BufferedReader(new FileReader("./data.csv"));
       String line;
       while ((line = br.readLine()) != null) {
         wholefile.add(line);
         String[] cols = line.split(",");
         id.add(cols[0]);
         property_address.add(cols[1]);
         first_name.add(cols[2]);
         last_name.add(cols[3]);
         email.add(cols[4]);
         owner_address.add(cols[5]);
         price.add(cols[6]);
       }
      System.out.println(id);
      System.out.println(property_address);
      System.out.println(first_name);
      System.out.println(last_name);
      System.out.println(email);
      System.out.println(owner_address);
      System.out.println(price);


   } catch (IOException e) {
       e.printStackTrace();
   }
}

当我 运行 这段代码时,我得到以下输出:

id = [id,1,2,3,4,5...]
property_address = [property address, 94032 Mockingbird Alley, 293 Haas Lane, 75 Ruskin Lane...]

等等,如我所料!

但是当我添加

date_sold.add(cols[7]);

我得到一个错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7

我不知道为什么有8列,我从0开始索引。 我的 while 语句有问题吗?

您正在调用的 split 版本删除了尾随的空字符串。

Trailing empty strings are therefore not included in the resulting array

您的第一行有 date_sold 列为空。尝试像这样调用拆分:

String[] cols = line.split(",", -1);

乍一看我没有发现任何错误,但我猜第二个条目的语句 line.split(",") 没有考虑最后一列是空的。 when 尝试使用 Sys.out 语句调试它并检查哪一行导致了问题。