user2472134
user2472134

Reputation: 63

break command does not stop the loop

Hello everyone, I have a code to get the first noun of a sentence from parsed result. I wrote the following code. But there seems to some problem. If statement does not break for loop. Can any one please help me to fix it?

Thanks in advance.

public static String Find_Noun(Parse p)
{    
  label: 
    for(Parse k:p.getChildren())
    {   
        if((k.getType()).equals("NN")||(k.getType()).equals("NNP")||
           (k.getType()).equals("NNS")||(k.getType()).equals("NNPS"))
        {
            noun=k.toString();              
            System.out.println(noun);
            break label;            // I am aware that label is not needed,
                                    // but it doesn't work either way.
        }
        else
        {
            System.out.println("else  "+k);
            Find_Noun(k);
        }
    }
    return noun;
}

Input:

became\VBD a\DT regular\JJ customer\NN of\IN a\DT suburban\JJ garden\NN

The output is:

else  became
else  became
else  a regular customer of a suburban garden
else  a regular customer
else  a
else  a
else  regular
else  regular
customer \\This is the string to be extracted
else  of a suburban garden
else  of
else  of
else  a suburban garden
else  a
else  a
else  suburban
else  suburban
garden
garden 

Upvotes: 0

Views: 160

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500825

The problem is that you're calling Find_Noun recursively on every non-noun. So yes, it is breaking out of the loop for the one iteration you're looking at... but then it's just getting back to the previous level of the stack.

It's not clear to me why you're recursing at all, but if you really do need to recurse, you need some way of detecting whether that recursive call actually found a noun or not, and returning immediately if it did. So possibly something like this:

// Renamed method to follow Java naming conventions
public static String findNoun(Parse p)
{    
    for(Parse k : p.getChildren())
    {   
        // Removed a bunch of extraneous brackets, and added whitespace
        // for readability. You should consider a set NOUN_TYPES
        // so you could use if (NOUN_TYPES.contains(k.getType()) instead.
        if (k.getType().equals("NN") || k.getType().equals("NNP") ||
            k.getType().equals("NNS")|| k.getType().equals("NNPS"))
        {
            return k.toString();
        }
        else
        {
            String possibleNoun = findNoun(k);
            // Return immediately if the recursion found a noun
            if (possibleNoun != null)
            {
                return possibleNoun;
            }
        }
    }
    // Nothing found in this node or children: tell the caller
    return null;
}

Upvotes: 4

Related Questions