-1

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); 
         }
    }
 }

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)
Kat Roz
  • 59
  • 9

2 Answers2

2

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());
}

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"
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

After solving problem with wrong input my code still didn't work, this time gave me ArrayIndexOutOfBoundsException. Maybe smn will have the same problem, so here is my solution.

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

Kat Roz
  • 59
  • 9