Java中Matcher在while loop中的异常行为

2024-11-26 10:03:07
推荐回答(1个)
回答1:

String loop = "a b c d e f g h i j k l";
Matcher loopMatcher = Pattern.compile("\\S+").matcher(loop);
boolean loopEnded = false;
while (!loopEnded) {
use(matcher);
if (matcher.hitEnd()) {
loopEnded = true;
}
}

public static void use(Matcher matcher) {
if (!matcher.find()) {
System.out.println("loop not ended but matcher hit end");
}
}
运行后发现会输出错误信息,循环到最后判断一下就好了。