NoSuchElementException, возникающий внутри кода - PullRequest
1 голос
/ 22 января 2020

Здесь я использовал два класса, чтобы объединить концепцию сериализации, десериализации и коллекций. Когда я запускаю программу, я получаю исключение времени выполнения «NoSuchElementException».

Я использовал класс Employee для хранения базовой c информации о Employee.

Класс DemoEmployee - это класс основной класс, в котором объявлены четыре метода.

  1. Чтобы добавить информацию о сотруднике (это объект в созданный мной объект Linked List).
  2. Чтобы отобразить информацию обо всем классе Employee объекты, присутствующие в объекте связанного списка.
  3. Для сериализации объекта связанного списка
  4. Для десериализации объекта связанного списка

    Как решить эту проблему?


import java.io.Serializable;

public class Employee_6033 implements Serializable {
    private int empid_6033;
    private String empname_6033;
    private String empdes_6033;
    private int empsalary_6033;

    public Employee_6033(int empid_6033, String empname_6033, String empdes_6033, int empsalary_6033) {
        // TODO Auto-generated constructor stub
        this.empid_6033 = empid_6033;
        this.empname_6033 = empname_6033;
        this.empdes_6033 = empdes_6033;
        this.empsalary_6033 = empsalary_6033;
    }

    int getEmpId_6033() {
        return empid_6033;
    }

    String getEmpName_6033() {
        return empname_6033;
    }

    String getEmpDes_6033() {
        return empdes_6033;
    }

    int getEmpSalary_6033() {
        return empsalary_6033;
    }
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class DemoEmployee_6033 {
    static List<Employee_6033> l_6033 = new LinkedList<Employee_6033>();
    int n_6033;
    int i_3033;

    void addEmployee_6033() {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the number of employees : ");
        n_6033 = input.nextInt();

        for (i_3033 = 1; i_3033 <= n_6033; i_3033++) {
            System.out.println("\nEnter Employee " + i_3033 + "'s Details :");
            System.out.print("\tEnter ID : ");
            int id_6033 = input.nextInt();
            input.nextLine();
            System.out.print("\tEnter Name : ");
            String name_6033 = input.nextLine();
            System.out.print("\tEnter Designation : ");
            String des_6033 = input.nextLine();
            System.out.print("\tEnter Salary : ");
            int salary_6033 = input.nextInt();

            l_6033.add(new Employee_6033(id_6033, name_6033, des_6033, salary_6033));
        }
        input.close();
    }

    void display_6033() {
        int j_6033 = 1;

        for (Employee_6033 ref_6033 : l_6033) {
            System.out.println("Employee " + j_6033);
            System.out.println("\tID : " + ref_6033.getEmpId_6033());
            System.out.println("\tName : " + ref_6033.getEmpName_6033());
            System.out.println("\tDesignation : " + ref_6033.getEmpDes_6033());
            System.out.println("\tSalary : " + ref_6033.getEmpSalary_6033());
            j_6033++;
        }
    }

    void serialize_6033() {
        try {
            String filename_6033 = "";
            Scanner input = new Scanner(System.in);
            System.out.print("Enter the name of the file you want to Read from : ");
            filename_6033 = input.nextLine();

            // Saving of object in a file
            FileOutputStream file_6033 = new FileOutputStream(filename_6033);
            ObjectOutputStream out_6033 = new ObjectOutputStream(file_6033);

            // Method for serialization of object
            out_6033.writeObject(l_6033);

            out_6033.close();
            file_6033.close();

            System.out.println("Object has been serialized");
            input.close();
        }

        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
    }

    void deserialize_6033() {
        l_6033 = null;
        try {
            String filename_6033;
            Scanner input = new Scanner(System.in);
            System.out.print("Enter the name of the file you want to Write to : ");
            filename_6033 = input.nextLine();
            // Reading the object from a file
            FileInputStream file_6033 = new FileInputStream(filename_6033);
            ObjectInputStream in_6033 = new ObjectInputStream(file_6033);

            // Method for deserialization of object
            l_6033 = (List<Employee_6033>) in_6033.readObject();

            in_6033.close();
            file_6033.close();

            System.out.println("Object has been deserialized ");
            display_6033();
            input.close();
        }

        catch (IOException ex) {
            System.out.println("IOException is caught");
        }

        catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException is caught");
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        DemoEmployee_6033 de_6033 = new DemoEmployee_6033();

        int choice_6033;
        do {
            System.out.println("\n********* MENU *********");
            System.out.println("--------------------------");
            System.out.println("1. Add Employee");
            System.out.println("2. Display Employee Details");
            System.out.println("3. Write Data into a File - Serialization");
            System.out.println("4. Read Data from a File - Deserialization");
            System.out.println("5. Exit");
            System.out.println("--------------------------");
            System.out.print("Enter you Choice : ");
            choice_6033 = input.nextInt(); //Error comes here after 1 iteration.
            switch (choice_6033) {
            case 1:
                de_6033.addEmployee_6033();
                break;
            case 2:
                de_6033.display_6033();
                break;
            case 3:
                de_6033.serialize_6033();
                break;
            case 4:
                de_6033.deserialize_6033();
                break;
            case 5:
                break;
            default:
                System.out.println("You have entered an invalid choice!");
                break;
            }
        } while (choice_6033 != 5);
        input.close();
    }

}

1 Ответ

0 голосов
/ 23 января 2020

NoSuchElementException выбрасывается, потому что вы набираете input.close() экстенсивно, где в вашем случае его следует вызывать только один раз. Я удалил input.close (); вхождения (кроме метода main), и ваш код работал нормально.

Есть причина для этого, что вызов Scanner.close() фактически закроет все System.in и каждый последующий вызов метода, например input.nextInt() в вашем случае, приведет к исключению.

...