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

标签 java exception iterator

我有一个 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/

相关文章:

java - 如何按天汇总?

java - OpenCV人脸检测找不到任何

python - 如何从列表理解中的单行中提取两个元组?

Rust 从迭代器中收集 HashMap

java - 比较 listIterator 中的元素

java - servlet 是否适合用于我的网站登录确认页面?

java - 如何在 View 完全渲染后进行回调?

C++ 问题中的异常

仅在调试时捕获 C# 异常?

java - 如何在Java中导入