Laura
Laura

Reputation: 29

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 it was the other loop that was the problem.

Upvotes: 1

Views: 4707

Answers (5)

mre
mre

Reputation: 44240

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

enter image description here

Upvotes: 3

D-zer0
D-zer0

Reputation: 63

There is no terminating condition in your while loop.

The exercise description on your linked page also states that the program does loop repeatedly.

Upvotes: 3

vcsjones
vcsjones

Reputation: 141638

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.

Upvotes: 3

Andrew White
Andrew White

Reputation: 53496

That while(true) never terminates!

Upvotes: 7

RMT
RMT

Reputation: 7070

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.

Upvotes: 10

Related Questions