将List <string []>转换为Array int [] []

时间:2017-01-11 19:58:46

标签: java csv opencsv

我需要使用OpenCSV库从csv-file读取矩阵。 OpenCSV函数readAll()返回List String [],而我需要int [] []。这就是我所拥有的:

 cSVFileReader = new CSVReader(new FileReader(path), ',');
 List<String[]> allRows = cSVFileReader.readAll();

 for(String[] row : allRows){
   for (int i = 0; i<cSVFileReader.getLinesRead(); i++){
        String[] numbers = row[i].split(" ");
        int [] ary = new int[numbers.length];
        int j = 0;
        for (String number : numbers){
        ary[j++] = Integer.parseInt(number); 
         }
    }
 }

这是输出:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at strassenalgorithm.CSVFile.readM(CSVFile.java:37)
at strassenalgorithm.Main.main(Main.java:26)

2 个答案:

答案 0 :(得分:2)

当您看到NumberFormatException时,您需要确定输入是否错误,或者您的代码是否错误。

如果输入错误,则需要添加在顶层产生漂亮错误的代码,例如

try {
    parseMyFile();
} catch (NumberFormatException nfe) {
    System.err.println("File contains invalid numbers: "+nfe.getMessage());
}

如果您想允许此输入,例如因为可以用空字符串代替数字,检查特定输入,或者在循环中捕获NumberFormatException

for (String number : numbers){
    if (number.length() != 0) {
        ary[j++] = Integer.parseInt(number); 
    } else {
        ary[j++] = 0; // In this case, zero is the same as "empty"
    }
}

答案 1 :(得分:0)

在解决了输入错误的问题后,我的代码仍然没有工作,这次给了我ArrayIndexOutOfBoundsException。也许smn会有同样的问题,所以这是我的解决方案。

private static int r;

public static int[][] readM(String path) throws FileNotFoundException, IOException {
   cSVFileReader = new CSVReader(new FileReader(path), ',');
    List<String[]> allRows = cSVFileReader.readAll();
    String[][] array = new String[allRows.size()][];
   for (int i = 0; i < allRows.size(); i++) {
       String[] row = allRows.get(i);
       array[i] = row;
       h = row.length;
       r++;
          }
   int[][] mResult = new int[r][h];
   for (int i =0; i<r; i++) {
      for (int j = 0; j< h; j++) {
          mResult[i][j] = Integer.parseInt(array[i][j]);
      } 
   }
   return mResult; }

意味着我有错误的方法。我需要的只是将字符串列表转换为2d数组的字符串,并在2d数组的int旁边