转换列表< String []>数组int [] [] [英] Convert List<String[]> to Array int[][]

查看:81
本文介绍了转换列表< String []>数组int [] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用OpenCSV库从csv文件读取矩阵.来自OpenCSV的readAll()函数返回列表String [],而我需要int [] [].这就是我所拥有的:

I need to read matrix from csv-file using OpenCSV library. Function readAll() from OpenCSV return List String[], while I need int[][]. This is what I have:

 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)

推荐答案

看到 NumberFormatException 时,您需要确定输入是否错误或代码错误.

When you see a NumberFormatException, you need to decide if your input is wrong, or your code is wrong.

如果您输入的错误,则需要添加代码,例如,在顶级生成会产生漂亮外观错误的代码.

If your input is wrong, you need to add code that produces a nice-looking error at the top level, e.g.

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

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

If you want to allow this input, e.g. because it's OK to have empty strings in place of numbers, check for specific input, or catch NumberFormatException inside the loop:

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"
    }
}

这篇关于转换列表&lt; String []&gt;数组int [] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆