Java 转换列表<;字符串[]>;到数组int[][]
我需要使用OpenCSV库从csv文件中读取矩阵。函数readAll()从OpenCSV返回列表字符串[],而我需要int[]。这就是我所拥有的:Java 转换列表<;字符串[]>;到数组int[][],java,csv,opencsv,Java,Csv,Opencsv,我需要使用OpenCSV库从csv文件中读取矩阵。函数readAll()从OpenCSV返回列表字符串[],而我需要int[]。这就是我所拥有的: cSVFileReader = new CSVReader(new FileReader(path), ','); List<String[]> allRows = cSVFileReader.readAll(); for(String[] row : allRows){ for (int i = 0; i<cSVFi
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);
}
}
}
当您看到
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"
}
}
在解决了输入错误的问题后,我的代码仍然无法工作,这次给了我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; }
私有静态int r;
公共静态int[][]readM(字符串路径)抛出FileNotFoundException、IOException{
cSVFileReader=newcsvreader(新文件读取器(路径),',');
List allRows=cSVFileReader.readAll();
字符串[][]数组=新字符串[allRows.size()][];
对于(int i=0;i 对于(int i=0;i是否尝试调试代码?似乎您正在将空字符串解析为整数。调试应该不难。您正在尝试将空白空格解析为数字。首先检查字符串是否为空或为空。您正在尝试将空字符串转换为数字。您需要定义处理空字符串的要求然后只尝试解析非空字符串。Apache commons中的StringUtils有实用方法来检查这一点。没有检查我正在使用的文件。它包含空格。谢谢
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; }