0

Hello I am having issues reading from csv file which contains 3 columns per row. I cant seem to parse the last cell (3) to an integer even though it is always a "parsable" string: Berlin,Buenos Aires,7402 I can't seem to get 7402 all the compiler throws is:

" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) at java.base/java.lang.Integer.parseInt(Integer.java:658) at java.base/java.lang.Integer.parseInt(Integer.java:776)

This is the code I have:

Scanner scan = new Scanner("worldcities.csv");
        scan.useDelimiter("[,\\n]"); // get everything before a comma or a newline
        while(scan.hasNext()) { // while this file has something then we
            edge.v1 = scan.next(); // take vertice1 ----> city 1
            edge.v2 = scan.next(); //take vertice2 ----> city 2
            edge.e = Integer.parseInt(scan.next()); // parse the third value as int(distance between city1 and city2)
            minheap.add(edge);
        }
        scan.close();

I seem to be able to get the first 2 values fine in the debugger.

the console just shows "

Aidan
  • 37
  • 1
  • 1
  • 4
  • https://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it – jose praveen Mar 24 '20 at 09:58
  • Which type of linebreaks are used in the CSV file? Your code works fine for \n (Unix), but not for e.g. \r\n (Windows). If you are on Windows, you might have to change your delimiter. – Pieterjan Deconinck Mar 24 '20 at 10:11
  • I tried using \r and it seems to solve the problem for the Integer part but it carries a \n to the next cell – Aidan Mar 24 '20 at 11:19

1 Answers1

0

You can iterate throught file lines with the nextLine() method, as in this example:

Scanner scanner = new Scanner(new File("worldcities.csv"));
while (scanner.hasNextLine()) {
    String columns[] = scanner.nextLine().split(",");
    edge.v1 = columns[0]; // take vertice1 ----> city 1
    edge.v2 = columns[1]; //take vertice2 ----> city 2
    edge.e = Integer.parseInt(columns[2]); // parse the third value as int(distance between city1 and city2)
    minheap.add(edge);
}
scanner.close();

or with using the Files class without the Scanner:

List<String> rows = Files.readAllLines(Paths.get("worldcities.csv"));
for (String row : rows) {
    String columns[] = row.split(",");
    edge.v1 = columns[0]; // take vertice1 ----> city 1
    edge.v2 = columns[1]; //take vertice2 ----> city 2
    edge.e = Integer.parseInt(columns[2]); // parse the third value as int(distance between city1 and city2)
    minheap.add(edge);
}

Also you can use a special library for working with CVS files, for example look at Apache Commons CSV library.

Ilya Lysenko
  • 1,772
  • 15
  • 24