0

以下 Java 过程导致 InputMismatchException 错误的原因是什么?

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

谢谢

4

1 回答 1

1

发生这种情况是因为hello[space]不是String. 由String空格分隔符标记,因此标记如下:

String input = "hello 12345\n";
Scanner s = new Scanner(input);

while(s.hasNext()){
    System.out.println(s.next());
}
//Outputs: Hello
//         12345

错误消息只是告诉您它无法hello[space]在标记中找到,它们是hello12345

如果您想查找模式而不考虑使用分隔符,请使用String#findInLine

s.findInLine("hello ");
于 2014-06-28T09:06:31.130 回答