Scanner delimiter not working as expectedwith input file (Java)

Viewed 1966

I am writing a program to read input from a text file that will always follow the format of char:int, such as the following:

A:3
B:1
C:2
D:2

(eof here)

I want to read in the characters and their corresponding numbers, ignoring the colons.

In my program I have the following declarations and initializations:

String fileName = "input.txt";
File file = new File(fileName);
Scanner in = new Scanner(file).useDelimiter(":");

Then, I try to read from my file using the following loop:

while(in.hasNextLine()){
        String t = in.next();
        int n = in.nextInt();
        ....
}

When I attempt to run my program in Eclipse, I receive the following error(s):

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at Huffman_Encoder.main(Huffman_Encoder.java:26)

i.e., the line: int n = in.nextInt(); is throwing an exception. I am not sure why this is the case. From my understanding of Scanner delimiters, I should be skipping over the colons and so int n = in.nextInt(); should put the value following the colon into n.

What am I not seeing here?

OS is Windows 10, if that matters. Thank you.

edit: upon further testing, I've pinpointed the error as occurring immediately after String t = in.next(); Printing out t immediately after this shows 'A', and then the program throws its exception at int n = in.nextInt();

2 Answers
Related