-1

I have a class Test with a static method to take input.

 class Test {
        public static Student readStudent() throws IOException {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter first name of student");
            String fname = s.nextLine();
            System.out.println("Enter middle name of student");
            String mname = s.nextLine();
            System.out.println("Enter last name of student");
            String lname = s.nextLine();
            System.out.println("Enter name format(1 for ',' and 2 for ';') ");
            int num = s.nextInt();
            System.out.println("Enter age of student");
            int age = s.nextInt();

            s.close();

            return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
                    mname, lname)), age);

        }
    }

I am able to take the input for one student but once i put it in a for loop i get a java.util.NoSuchElementException: No line found error.

This is my loop

for (int i = 0; i < 10; i++) {
            Student s = Test.readStudent();
        }

Why am I getting this error? Thanks.

rohit_r
  • 623
  • 1
  • 6
  • 18

1 Answers1

2

s.close(); closes the current Scanner object, but also all underlying streams, which is System.in in this case. Once your standard input stream is closed, you cannot open it anymore.

So all in all it would be best to close your Scanner after you're sure you won't need it anymore and restructure your code like this:

Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
    Student s = Test.readStudent(sc);
    // do something with your student object here
}
sc.close();

And change your method to

public static Student readStudent(Scanner s) throws IOException {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter first name of student");
    String fname = s.nextLine();
    System.out.println("Enter middle name of student");
    String mname = s.nextLine();
    System.out.println("Enter last name of student");
    String lname = s.nextLine();
    System.out.println("Enter name format(1 for ',' and 2 for ';') ");
    int num = s.nextInt();
    s.nextLine(); // Need to consume new line
    System.out.println("Enter age of student");
    int age = s.nextInt();
    s.nextLine(); // Need to consume new line

    // no closing here

    return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
                mname, lname)), age);
}
QBrute
  • 4,405
  • 6
  • 34
  • 40
  • 2
    Or not close it at all. Resources should be closed by the one who opened them. The JVM in this case. And the JVM correctly closes `System.in` at shutdown. – Zabuzard Sep 20 '19 at 11:04