【发布时间】:2018-01-29 04:12:21
【问题描述】:
我有这个 CSV 文件:
World Development Indicators
Number of countries,4
Country Name,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014
Bangladesh,6.28776238,13.20573922,23.46762823,30.16828408,34.35334451,44.94535882,55.19256723,62.82023906,74.42964608,80.03535051
"Bahamas, The",69.21279415,75.37855087,109.340767,102.7875065,101.2186453,118.8292307,81.5628489,80.65383375,76.05187427,82.29635806
Brazil,46.31418452,53.11025849,63.67475185,78.5549801,87.54187651,100.8810115,119.0023853,125.0018521,135.3050481,138.9514906
Germany,94.55486999,102.2828888,115.1403608,126.5575074,126.2280577,106.4836959,109.6595675,111.5940398,120.9211651,120.4201855
我正在尝试将国家/地区的数据(双倍一次)存储到一个矩阵(双倍 [][])中。这是我到目前为止的代码:
public double[][] getParsedTable() throws IOException {
double[][] table = new double[4][10];
String row;
int indexRow = 0;
int indexColumn = 0;
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine();
br.readLine();
String line = br.readLine();
while(line != null && !line.isEmpty()){
line = br.readLine();
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for(int i = 1; i < array.length; i++){
table[indexRow][indexColumn] = Double.parseDouble(array[i]);
indexColumn++;
}
indexColumn = 0;
indexRow++;
}
System.out.print(Arrays.deepToString(table));
return table;
}
我得到一个错误:NullPointerException at:
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
我不知道为什么。我尝试了不同的组合。似乎没有任何效果。它似乎从 CSV 文件中提取数字并存储它们,但是当我调用时:
System.out.print(Arrays.deepToString(table));
它不会打印出任何东西,因此我无法检查它是否正确存储。能否告诉我:1. Why I am getting an error. 2. Why System.out.println does not print out an array. 谢谢
【问题讨论】:
-
您的 CSV 文件格式不正确,标题必须在行首
-
@ArifMustafa 这个 CSV 文件由我的导师提供。我不能改变它。
-
查看此维基CSV example。