0

I created an Employee class:

public class Employee {
    String name;
    double salary;
void getData() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\tName: \n\t");
        name = scanner.nextLine();

        System.out.print("\tSalary: \n\t");
        salary = scanner.nextDouble();

        scanner.close();
    }
    .
    .

Then, I created array of objects:

Employee[] employees = new Employee[num];

for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
 }

But, when I call this getData() method using loop, exception throws:

for (int i = 0; i < employees.length; i++) {
                employees[i].getData();
            }

I can't see why this error occurs

Shivam Jha
  • 1,204
  • 7
  • 23
  • use `scanner.next()` for string. refer this -- https://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class#:~:text=next()%20can%20read%20the%20input%20only%20till%20the%20space.,-It%20can't&text=separated%20by%20space.-,Also%2C%20next()%20places%20the%20cursor%20in%20the%20same%20line,cursor%20in%20the%20next%20line. –  Aug 03 '20 at 16:12
  • Put the exception here – Tashkhisi Aug 03 '20 at 18:02

1 Answers1

0

Due to close(), API on scanner underlying reader object get closed due to which not able to take next input. You can refer here for more details.

Do not create and close the scanner object each time. Instead of it create only once and close at the end of your program that will help.

  • But, it also gets reinitialized on every next call – Shivam Jha Aug 03 '20 at 15:32
  • Due to close API, System.in input stream is getting closed with scanner, in next initialize call, only the scanner gets initialized with the closed System.in input stream, so you are not able to take input again from that input stream. – Shivkumar Kawtikwar Aug 05 '20 at 05:34