java - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 for correctly indexed array
问题描述
I have a CSV file with 8 columns:
I have put each column into an array with the following code
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();
}
}
when I run this code I get the following output:
id = [id,1,2,3,4,5...]
property_address = [property address, 94032 Mockingbird Alley, 293 Haas Lane, 75 Ruskin Lane...]
and so on just like I expect!
However when I add
date_sold.add(cols[7]);
I get a error that
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
I do not know why as there are 8 columns and I have started indexing from 0. Is there something wrong with my while statement ?
解决方案
您正在调用的split版本会删除尾随的空字符串。
因此,尾随空字符串不包含在结果数组中
您的第一行的date_sold
列是空的。尝试像这样调用 split :
String[] cols = line.split(",", -1);
推荐阅读
- reactjs - 如何修复此打字稿承诺错误?
- android - ItemTouchHelper.callback 中的 ConvertToAbsoluteDirection()
- javascript - 使用 vue.js,如何设置带有嵌入式子项的动态路由器链接?
- java - 获取存储库中 Maven 工件的依赖项列表
- android - 如何在将“firebase_messaging_auto_init_enabled”设置为“false”并检索令牌/推送消息后启用 Firebase
- ios - 使用 UIAlertController 将某些视图排除在变暗之外
- c# - 将数据从 Excel 粘贴到 DataGridView
- android-studio - 如何修复:“com.xxx.xxxx.MainActivity”不能分配给“android.app.Activity”少
- python - 由于 Python 导入失败,无法执行克隆的 GitHub 存储库
- ruby-on-rails - 当我使用提供 swagger 和 rspec 功能的 gem 时出现路由问题