After using the scanner.close() method, I cannot open another scanner. I have searched my question on google to only find people giving a solution for a workaround. I just want to understand why this is a problem in the first place. can anyone explain why?
import java.util.Scanner;
public class Main {
public static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
scan.close();
Scanner scan = new Scanner(System.in);
System.out.println(scan.next()); //NoSuchElementException
}
}
I understand that having multiple scanners open at once can result in an outOfMemoryError, so I thought why not have it as a singleton utility class that you can call methods from? This class would open and close a scanner with each use so that streams do not need to remain open.
public class Main {
public static void main(String[] args) {
LinkedList<Scanner> list = new LinkedList<>();
while(true) {
list.add(new Scanner(System.in)); //OutOfMemoryError
}
}
}
which comes back to the root of my question, If we can all understand why the scanner class works this way, perhaps we could come up with a solution?