Search code examples
javajava.util.scannerinputmismatchexception

Java InputMismatchException error. What causes it?


What is the reason why that the following Java procedure causes a InputMismatchException error?

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        String input = "hello 12345\n";
        Scanner s = new Scanner(input);
        s.next("hello ");
    }
}

Thank you


Solution

  • This is occurring because hello[space] is not a token in the String. The String is being tokenized by a whitespace delimiter so the tokens are as follows:

    String input = "hello 12345\n";
    Scanner s = new Scanner(input);
    
    while(s.hasNext()){
        System.out.println(s.next());
    }
    //Outputs: Hello
    //         12345
    

    The error message is simply telling you that it cannot find hello[space] amongst the tokens, which are hello and 12345.

    If you want to find the pattern regardless of delimiters use, String#findInLine:

    s.findInLine("hello ");