使用scanner.close()方法后,无法打开其他扫描仪。我已经在Google上搜索了我的问题,仅找到提供解决方案的人。我只想首先理解为什么这是一个问题。谁能解释为什么?
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
}
}
Run Code Online (Sandbox Code Playgroud)
我知道一次打开多个扫描器会导致outOfMemoryError,所以我想为什么不将其作为可以从中调用方法的单例实用工具类?此类会在每次使用时打开和关闭扫描仪,因此流无需保持打开状态。
public class Main {
public static void main(String[] args) {
LinkedList<Scanner> list = new LinkedList<>();
while(true) {
list.add(new Scanner(System.in)); //OutOfMemoryError
}
}
}
Run Code Online (Sandbox Code Playgroud)
这回到了我的问题的根源,如果我们都能理解为什么扫描器类以这种方式工作,也许我们可以提出一个解决方案?