我必须从stdin读取整数,它具有以下格式:
{4:11},{23:29},{1:7}...
我尝试使用扫描仪定界符,但我认为first '{'
Scanner scanner = new Scanner(System.in).useDelimiter("\\D");
while (scanner.hasNext()){
int x = scanner.nextInt();
int y = scanner.nextInt();
}
我收到此异常:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Algorithm.main(Algorithm.java:63)
答案 0 :(得分:2)
您正在使用以下
指定分隔符模式 scanner.userDelimiter("\\D"); // This \\D is pattern which will be matched.
您需要按如下所示指定模式:
scanner.userDelimiter("\\D+") // With + keyword you are saying that it can be 1 or more.
最新的工作代码应如下所示:
Scanner scanner = new Scanner(System.in).useDelimiter("\\D+");
while(scanner.hasNext()){
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println("x: " + x);
System.out.println("y: " + y);
}
另一个示例是使用正则表达式显式解析该字符串,如果您仅查找分隔符模式匹配,则可能不需要这样做。
注意:由于您使用nextInt()而不验证输入,因此如果输入无效(不同的输入不包含int),则将获得异常
答案 1 :(得分:1)
您只需要提取连续的数字序列,而不考虑定界符。您可以逐行阅读输入并使用\d+
正则表达式进行解析:
Pattern pattern = Pattern.compile("\\d+");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println(matcher.group());
}
}