转换列表< 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"
}
}