【问题标题】:break command does not stop the loopbreak 命令不会停止循环
【发布时间】:2013-07-19 17:05:59
【问题描述】:

大家好, 我有一个代码可以从解析结果中获取句子的第一个名词。我写了以下代码。但似乎有些问题。 if 语句不会中断 for 循环。谁能帮我解决一下?

提前致谢。

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;
}

输入:

成为\VBD a\DT常规\JJ客户\NN of\IN a\DT郊区\JJ花园\NN

输出是:

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 

【问题讨论】:

  • break; 没有损坏。使用调试器单步调试代码,您会发现出了什么问题。

标签: java loops for-loop break


【解决方案1】:

问题是您在 every 非名词上递归调用 Find_Noun。所以是的,它正在为你正在查看的一次迭代打破循环......但它只是回到堆栈的上一层。

我不清楚你为什么要递归,但如果你真的确实需要递归,你需要一些方法来检测递归调用是否真的找到了一个名词,并且如果确实如此,请立即返回。所以可能是这样的:

// 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;
}

【讨论】:

  • 应该是“if (possibleNoun != null)”吗? (如何再次格式化代码样式的 cmets?)
  • 非常感谢它的工作。但我有一个问题。如果 break 命令只中断一次迭代,如何从所有剩余的迭代中停止循环?
  • @user2472134:不,它完全停止了那个循环...但是由于递归,你有几个循环在不同的堆栈级别同时运行。这就是让你感到困惑的原因。
  • 哦,好的。现在我懂了。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多