Iterator抛出NoSuchElementException的问题

时间:2013-03-13 23:28:14

标签: java iterator try-catch

我正在尝试编写一个随机化人群的程序。我遇到了Iterator的问题。 这是代码:

@SuppressWarnings("deprecation")
public static void results(List<String> nameslist) {

    Scanner scan = new Scanner(System.in);
    int groups = 0;
    int count = nameslist.size();
    int done=0; 

    do{
        System.out.println("How many people do you want per group?");
        groups = scan.nextInt();
    } while(groups == 0);
    Iterator itr = nameslist.listIterator();
    int peopledone=0;
    while(peopledone<count){    
    int groupsdone = 0;
    while (groupsdone <= groups){
        groupsdone++;
        peopledone = 0;
        System.out.println("Group "+groupsdone+":");
        while (peopledone <= groups){
            try{
                Object obj = itr.next();
                System.out.println(obj);
                peopledone++;
            }catch (NoSuchElementException e){
                System.out.println("Error");
                Thread.currentThread().stop();
            }
        }
    }   
}

有几点需要注意:

  • nameslist是我为了测试目的而放在一起的字母(a-f)列表。通常情况下,他们会成为班上人的名字。

  • 我试图让它只是列出名字,直到它用完为止。

非常感谢!

2 个答案:

答案 0 :(得分:0)

获取NoSuchElementException是因为嵌套循环导致迭代次数过多。一旦到达列表的末尾,如果再次调用迭代器上的next(),则会抛出该异常。

除非我误解了你想要做的事情,否则这应该有用(可能有一种更优雅的方式,但它至少可以解决你的问题):

public static void results(List<String> namesList)
    {
        Scanner scan = new Scanner(System.in);
        int namesPerGroup = 0;
        while (namesPerGroup == 0)
            namesPerGroup = scan.nextInt();

        int group = 0;
        int namesInGroup = 0;
        System.out.println("Group " + group + ": ");
        for (String name : namesList)
        {
            if (namesInGroup == namesPerGroup)
            {
                group++;
                namesInGroup = 0;
                System.out.println("Group " + group + ": ");
            }
            System.out.println(name);
            namesInGroup++;

        }
    }

答案 1 :(得分:0)

迭代次数比列表元素多 - 确保循环循环次数。

你想做的事情可以而且应该分两行完成:

    Collections.shuffle(nameslist);
    List<String> result = nameslist.subList(0, Math.min(count, nameslist.size()));