简体   繁体   中英

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

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 ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM