D
D
Den4_x2020-09-10 17:59:05
Java
Den4_x, 2020-09-10 17:59:05

NoSuchElementException error in Java Iterator, why did it occur (code in writing)?

package com.company.Labs.lab_5.My_Student_ex3;

import java.util.*;

public class Main {
    public static void main(String[] args) {

        //Задание 3 (пределал код из файла, так проще, смысл тот же)
        ArrayList students = new ArrayList();

        students.add(new Student(0, "Daniil", "ИСвГС", 182));
        students.add(new Student(0, "a", "ИСвГС", 182));
        students.add(new Student(0, "s", "ИСвГС", 180));
        students.add(new Student(0, "d", "ИСвГС", 170));
        students.add(new Student(0, "f", "ИСвГС", 183));
        students.add(new Student(0, "h", "ИСвГС", 172));
        students.add(new Student(0, "g", "ИСвГС", 192));
        students.add(new Student(0, "j", "ИСвГС", 152));
        students.add(new Student(0, "k", "ИСвГС", 182));
        students.add(new Student(0, "u", "ИСвГС", 171));
        students.add("String");

        print_iter(students);
    }

    public static void print_iter(List list) {
        Iterator iter = list.iterator();

        while (iter.hasNext()) {
            if (iter.next() instanceof Student) {
                Student student_object = (Student) iter.next();
                student_object.print();
            } else if (iter.next() instanceof String) {
               String str = (String)iter.next();
               int legth = str.length();
               System.out.println(legth);
            }

        }
    }
}

spoiler
5f5a3ea927fd8440006449.png


and I also noticed that he didn’t display all the data, that is, he didn’t display every ArrayList object + lines at the end. Basically rubbish. When I did it through the for loop, everything worked without errors and output exactly each object, what's the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-09-10
@Den4xCode

For one check for the presence of the next element, you perform four transitions to the next elements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question