Reputation: 78
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
Upvotes: 0
Views: 524
Reputation: 94429
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 ");
Upvotes: 1