【问题标题】:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 for correctly indexed array线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 7 用于正确索引的数组
【发布时间】:2018-05-28 00:07:30
【问题描述】:

我有一个包含 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]);

我收到一个错误

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 7

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

【问题讨论】:

  • 当您使用调试器单步执行代码时,您观察到了什么?

标签: java arrays csv bufferedreader indexoutofboundsexception


【解决方案1】:

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

因此,结果数组中不包含尾随的空字符串

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

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

【讨论】:

  • 非常感谢,我可以在 6 分钟内打勾,对不起,我的排名也不足以投票
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2013-02-14
    • 2012-10-29
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多