Search code examples
javajava.util.scannerinputmismatchexception

Java InputMismatchException unknown source


I am having trouble finding the source of my error. All I am doing is reading text from a file

public static void main(String[] args) throws Exception {
    int T;

    Scanner sc = new Scanner(new FileInputStream("problem3.txt"));

    T = sc.nextInt(); // first int in file, so T should be 2
}

and the error message shows an InputMismatchException:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at round1.Problem3.main(Problem3.java:11)

The content of problem3.txt is as following (3 lines, no spaces):

2
36
127

I have searched for other questions addressing InputMismatchException, but most have errors with 'wrong format' (trying to read ints as Strings, or vice versa). But in my case it shouldn't have a problem since the file contents are all integers.

I've also thought the error might be with the 'new line character (\n)'. So tried

T = sc.nextInt(); // error
sc.nextLine();

and the other way around

sc.nextLine();
T = sc.nextInt(); // error

Both still give the same error, on the same line.

Seems like a simple issue, but I just can't find it. Thanks in advance.


Problem solved: I changed the encoding to Cp1252 and it reads the 2. Thanks all


Solution

  • It is an Encoding Problem. Try to use UTF-8 or ANSI and your Code should run fine without any problem.