Carefully Closing a Scanner

suggest change

If you construct a Scanner on System.in, closing that scanner also closes System.in. Later reads on that stream, including through another Scanner, then fail. A scanner that you closed throws IllegalStateException. A scanner whose underlying stream was closed typically throws NoSuchElementException.

example:

Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
int x1 = sc1.nextInt();
sc1.close();
// java.util.NoSuchElementException
int x2 = sc2.nextInt();
// java.lang.IllegalStateException
x2 = sc1.nextInt();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents