gpt4 book ai didi

java - break命令不会停止循环

转载 作者:行者123 更新时间:2023-12-01 18:46:09 26 4
gpt4 key购买 nike

大家好, 我有一个代码可以从解析结果中获取句子的第一个名词。我写了下面的代码。但似乎有些问题。 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;
}

输入:

became\VBD a\DT regular\JJ customer\NN of\IN a\DT suburban\JJ garden\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

最佳答案

问题是您在每个非名词上递归调用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;
}

关于java - break命令不会停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com