1

When i use scanner.close(), System.in parameter is also closed.
I can understand a little this process with searching this site.
Some said if System.in is closed, it can't be reopened.
But they didn't have conviction for that.


So my question is this:
How to System.in reopen? or is that impossible?


for understanding my question, i put some example code here

public void scannerTest() {
    Scanner input = new Scanner(System.in);
    int i = input.nextInt();
    input.close();
    Scanner input2 = new Scanner(System.in);
    int j = input2.nextInt();
}

and result on console

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at repeat.Test.scannerTest(Test.java:55)
at repeat.Test.<init>(Test.java:19)
at repeat.Test.main(Test.java:11)
Lucky Day
  • 11
  • 3
  • It's impossible. Once it's closed, it's closed. – Andy Turner Feb 27 '17 at 23:46
  • Why are you asking this? Why would you want to close it? – shmosel Feb 27 '17 at 23:48
  • You've reopened it in a new instance; simply use that instance: `int j = input2.nextInt();` – CynePhoba12 Feb 27 '17 at 23:52
  • If System.in can't reopen, is there any reason using 'scanner.close()'? – Lucky Day Feb 27 '17 at 23:53
  • @CynePhoba12 sorry. my code is some error. i edit it now. but still I found error – Lucky Day Feb 27 '17 at 23:55
  • There is a reason, but only at the very end of the code... You only need **one** `Scanner`, though, to read many values. – OneCricketeer Feb 27 '17 at 23:55
  • @cricket_007 i know I can put the 'close' method at the very end of the code. But in view of resource, I think, that is useless, because program will end very soon. is that wrong? – Lucky Day Feb 28 '17 at 00:02
  • @AndyTurner thanks for link. That is i want to find. – Lucky Day Feb 28 '17 at 00:10
  • It will be garbage collected, yes. The close method only exists because that class implements `Closeable` for other reasons. If the option to remove that method just because you used `System.in` existed, then someone would have done that. In other words, you can use `Scanner` for more than that. – OneCricketeer Feb 28 '17 at 00:10
  • @cricket_007 I'm not native speaker so that I can't perfectly understand what you say. is that correct that i understand? _It is necessary because it is existed._ – Lucky Day Feb 28 '17 at 00:58
  • Nevermind... My point is that `System.in` is not the only variable for Scanner usage, and for those others, closing makes sense – OneCricketeer Feb 28 '17 at 03:25

0 Answers0