【发布时间】: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