while(Matcher.find()) is looping infinitely
I modified the following code from Oracle's Java Tutorials:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args){
while (true) {
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher("foo foo foo");
boolean found = false;
while (matcher.find()) {
System.out.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end());
found = true;
}
if(!found){
System.out.format("No match found.%n");
}
}
}
}
I am trying to learn how to use regular expressions in Java. (I feel pretty confident about regex's, just not with Java's classes for using them.) I am using Eclipse, which I am also not incredibly familar with. I could not figure out how to get the console to not be initialized to null (as the tutorial warned), so I removed it and am just using static values and recompiling every time I want to try something new.
When I run this code, I get an infinite loop:
I found the text "foo" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 4 and ending at index 7.
I found the text "foo" starting at index 8 and ending at index 11.
I found the text "foo" starting at index 0 and ending at index 3.
etc., etc., etc. until I hit terminate
What am I doing wrong?
Thanks.
Nevermind... >.< For some reason I didn't see the infinite loop on the outside. I assumed the whole time that开发者_JAVA技巧 it was the other loop that was the problem.
You currently have a while(true)
arround that section of your code. while(true)
is an infinite loop, and you never seem to break out of it.
That while(true)
never terminates!
The external while(true)
loop is just for demo purposes so that it can keep asking you for input. You don't need to keep asking for input; so the while(true)
loop should be removed.
There is no terminating condition in your while loop.
The exercise description on your linked page also states that the program does loop repeatedly.
while(true){...}
is known as an infinite loop. The only way to stop the execution of such a loop is to insert a break
, otherwise you'll be stuck in that block of code
精彩评论