InputMismatchException when working with the scanner

Why does an error occur if you uncomment a commented-out line?

In the file, one line is exactly the same as assigned to the line variable.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
    String line = br.readLine();
    System.out.println("\"" + line + "\"");
    // line = "376 933";
    System.out.println("\"" + line + "\"");
    int n1;
    int n2;
    try (Scanner lineScanner = new Scanner(line)) {
        n1= lineScanner.nextInt();
        n2= lineScanner.nextInt();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Error

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
Metro.readMetro(Metro.java:21) at
Metro.main(Metro.java:64) "376 933"
"376 933"

2 answers

Still, there was a problem with the encoding. The file is originally in French. the language with their additional letters. But what does a string with numbers and a space have to do with it, I didn't understand. Numbers and spaces are the usual characters from the first 127...

 1
Author: Олексій Моренець, 2017-11-19 08:17:44

Very strange, I ran the following code in my

public static void main(String[] args) {
        String line = "376 933";
        System.out.println("\"" + line + "\"");
        int n1;
        int n2;
        try (Scanner lineScanner = new Scanner(line)) {
            n1= lineScanner.nextInt();
            n2= lineScanner.nextInt();
        }
       System.out.println(n1);
       System.out.println(n2);
}

Result:

"376 933"
376
933

And no mistakes.

Try running my code, it looks like you have the wrong class being executed, or the class file has some tricky encoding, which makes the space not recognized as a space in Java.

 0
Author: Slava Vedenin, 2017-11-18 23:54:36