当我正在检查事先是否有元素时,为什么抛出NoSuchElement Exception?

时间:2013-01-28 21:51:21

标签: 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()确保我正在处理一个元素。

1 个答案:

答案 0 :(得分:4)

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

我会替换

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

通过

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