gpt4 book ai didi

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 7 for correctly indexed array

转载 作者:行者123 更新时间:2023-12-02 11:11:55 25 4
gpt4 key购买 nike

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

enter image description here

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

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 列为空。尝试像这样调用 split:

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

关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 7 for correctly indexed array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50557618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com