Carefully Closing a Scanner
suggest changeIf 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();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents