gpt4 book ai didi

java - 当我事先检查是否存在元素时,为什么会引发 NoSuchElement 异常?

转载 作者:行者123 更新时间:2023-12-01 18:54:29 25 4
gpt4 key购买 nike

我有一个 JSP 页面,用户可以在其中选择多个复选框(最多 10 个)。有时,如果选中多个复选框,则会引发 NoSuchElement 异常。

Servlet 代码:

 Iterator<ClassInfo> iterateCurrentResultSet = resultSet.iterator();

//If the current class's location isn't contained in "locations", the user didn't select it so remove
//It from the results.
while(iterateCurrentResultSet.hasNext())
{
//Evaluate every location they checked for, remove any class that isn't one of these locations.
for(String selectedLocation : locations)
{
//IF THE EXCEPTION OCCURS, IT DOES HERE. Current class location, it this doesn't match the user's selected criteria, it's removed.
String currentClassLocation = iterateCurrentResultSet.next().getSectionLocation();

//Check if the user wants to see other classes, if not, continue on.
if(selectedLocation.equals("OTH"))
{
//If this is false, keep it because it is an "Other" class, such as SFD, CWD, etc.
if(mainCampusCode.contains(currentClassLocation))
{
iterateCurrentResultSet.remove();
}//doNothing();
}
else
{
//If it does not have one of the selected locations, remove it.
if(!currentClassLocation.contains(selectedLocation))
{
iterateCurrentResultSet.remove();
}//doNothing();
}

}
}

我不确定为什么会抛出它,正如我从 JavaDoc 中了解到的,如果没有元素,似乎会发生这种情况,但我认为 iterateCurrentResultSet.hasNext() 确保我正在处理一个元素。

最佳答案

您在外循环中检查 iterateCurrentResultSet.hasNext(),但如果有多个 位置,则调用 next()在 for 循环中多次。

我会替换

String currentClassLocation = iterateCurrentResultSet.next().getSectionLocation();

if(!iterateCurrentResultSet.hasNext())
break; // exit for-loop if there is no next
String currentClassLocation = iterateCurrentResultSet.next().getSectionLocation();

关于java - 当我事先检查是否存在元素时,为什么会引发 NoSuchElement 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571903/

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