Why am I getting an InputMismatchException with?

Voyex :

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:

Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2

When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an int).

public void fileScanner(File toScan) throws FileNotFoundException {
            Scanner sc = new Scanner(toScan);
            sc.useDelimiter(",");
            System.out.println(sc.next());
            System.out.println(sc.nextInt());
            System.out.println(sc.nextInt());

Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.

backdoor :

You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-

Scanner sc = new Scanner(toScan);
        sc.useDelimiter(",|\\r\\n");
        while (sc.hasNext()) {
            System.out.println(sc.next());
            System.out.println(sc.nextInt());
            System.out.println(sc.nextInt());
        }

OUTPUT:-

Abbotsford
2310
2

Adams
1967
1

Algoma
3167
2

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407468&siteId=1