[英]Convert List<String[]> to Array int[][]
I need to read matrix from csv-file using OpenCSV library. 我需要使用OpenCSV库从csv文件读取矩阵。 Function readAll() from OpenCSV return List String[], while I need int[][].
来自OpenCSV的readAll()函数返回List String [],而我需要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);
}
}
}
And this is output: 这是输出:
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)
When you see a NumberFormatException
, you need to decide if your input is wrong, or your code is wrong. 当看到
NumberFormatException
,您需要确定输入是否错误或代码是否错误。
If your input is wrong, you need to add code that produces a nice-looking error at the top level, eg 如果您输入的错误,则需要添加代码,以在顶层产生美观的错误,例如
try {
parseMyFile();
} catch (NumberFormatException nfe) {
System.err.println("File contains invalid numbers: "+nfe.getMessage());
}
If you want to allow this input, eg because it's OK to have empty strings in place of numbers, check for specific input, or catch NumberFormatException
inside the loop: 如果要允许此输入,例如,因为可以使用空字符串代替数字,请检查特定的输入,或者在循环内捕获
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"
}
}
After solving problem with wrong input my code still didn't work, this time gave me ArrayIndexOutOfBoundsException. 解决输入错误的问题后,我的代码仍然无法正常工作,这次给了我ArrayIndexOutOfBoundsException。 Maybe smn will have the same problem, so here is my solution.
也许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; }
means I had wrong approach. 表示我的方法错误。 All I need was to convert List of Strings to 2d array of Strings, and next to 2d array of int
我需要做的就是将字符串列表转换为2d字符串数组,然后转换为int的2d数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.