wkwkwk
wkwkwk

Reputation: 163

InputMismatchException when trying to to read data from .csv file

I'm trying to read data from a .csv file, but I'm getting an InputMismatchException error. The .csv file looks like this:

39.743222, -105.006241, Stringa
39.743981, -105.020017, Stringb
39.739377, -104.984774, Stringc
39.627779, -104.839291, Stringd
39.731919, -104.961814, Stringe

and my code to read the file is:


        Scanner in = new Scanner(new FileInputStream(ROUTE_DATA_FILE));
        in.useDelimiter(",");

        double cLat, cLong;
        String cName;

        while (in.hasNextLine()) {
            cLat = in.nextDouble();
            cLong = in.nextDouble();
            cName = in.next();

            System.out.println(cLat);
            System.out.println(cLong);
            System.out.println(cName);
        }

The error message is:

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at RouteDriver.<init>(RouteDriver.java:45)
    at RouteDriver.main(RouteDriver.java:142)

Process finished with exit code 1

I would really appreciate any help on this. Thank you.

Upvotes: 1

Views: 169

Answers (1)

Try this::

        Scanner in = new Scanner(new FileInputStream(ROUTE_DATA_FILE));
        in.useDelimiter(",");
        double cLat, cLong;String cName;

        while (in.hasNextLine()) {
            cLat = in.nextDouble();
            cLong = in.nextDouble();
            cName = in.nextLine(); // in.next() reads the string as well as the next double value. in.nextLine() will read only the String

            System.out.println("cLat=>"+cLat+" cLong=>"+cLong+" cName=>"+cName);
        }

Let me know if it helps

Upvotes: 1

Related Questions