这是我使用while循环的方法。我强烈怀疑无限循环是可能的。如何检查和消除?
我在这里使用两个while循环。我可以完全拆除while循环吗?
public class ReferenceListSaveHandler
{
public PublishReferenceListUpdates populateResponse(SearchQueryResponse pSearchQueryResponse,SearchQueryResponse pListResponse, ObjectFactory objFactory) throws IOException, ParserConfigurationException, SAXException,SipException, Exception
{
ReferenceDataProcessor lRefPro = new ReferenceDataProcessor();
PublishReferenceListUpdates lResponse = null;
Record listRecord = null;
ReferenceDataListItemListType lReferenceDataListItemListType = objFactory
.createReferenceDataListItemListType();
ReferenceDataListType lReferenceDataListType = null;
ReferenceDataListItemType lReferenceDataListItemType = null;
boolean ifSynonym = false;
String lRowIdObject = null;
final int lRowIdLength = 14;
if (refListItemItr.hasNext())
{
Record record = (Record)refListItemItr.next();
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing)
{ // first use of while loop
if (refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if (continueProcessing)
{
lSynonymListType = objFactory
.createSynonymListType();
Field itemLSIDField = record
.getField(ReferenceDataConstants.FIELD_COMPOUND_ASSET_ID);
if (itemLSIDField == null)
{
continue;
}
else
{
currentItemLSID = itemLSIDField
.getStringValue().trim();
}
lReferenceDataListItemType = objFactory
.createReferenceDataListItemType();
lReferenceDataListItemType = setListDetails(record,
lReferenceDataListItemType,
lId, lName, objFactory);
while (refListItemItr.hasNext()
&& continueProcessing)
{ // second use of while loop
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
continueProcessing = true;
}
}//while loop
}
}
}
请帮忙。
答案 0 :(得分:1)
第一个问题:refListItemItr
,无论是什么(其定义未显示),都有一个.next()
方法,但它从不在循环中调用。
问题二:如果你输入第二个while
循环总是无限的:
while (refListItemItr.hasNext()
&& continueProcessing)
{
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
此循环内部refListItemItr.hasNext()
和continueProcessing
均无法更改。这就是为什么它是一个无限循环。
编辑: 我无法告诉你如何更改代码,因为有很多可能的方法来改变它,具体取决于应该发生的事情。你可以尝试这个,但它可能会或可能不会工作:
在第一个循环结束之前添加此行:
record = (Record)refListItemItr.next(); // ADD THIS LINE
} //while loop BEFORE THIS LINE
答案 1 :(得分:0)
这是一个无限循环,外循环取决于lastrecord
,它在程序的任何地方都没有设置为true
答案 2 :(得分:0)
每当我写下while
这个词时,我就会抛出一个循环计数器,如下所示:
int loopCounter = 0, maxLoops = 1000; //just an example
while((loopCounter++) < maxLoops && (myConditions))
{
// loop away, this can't ever be infinite
}
或者
int loopCounter = 0, maxLoops = 1000; //just an example
do
{
// loop away, this can't ever be infinite
}
while((loopCounter++) < maxLoops && (myConditions))
当然,maxLoops
的大小总是比任何合理的迭代次数大几个数量级...然后我添加一个检查:
if (loopCounter == maxLoops) { throw new InvalidOperationException("Infinite loop detected!"); }