Closing a Scanner throws java.util.NoSuchElementException

When you are reading using Scanner from System.in, you should not close any Scanner instances because closing one will close System.in and when you do the following, NoSuchElementException will be thrown.

Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
...
sc1.close();
...
...
Scanner sc2 = new Scanner(System.in);
String newStr = sc2.nextLine();      // Exception!

Leave a Comment