Scanner 是一个流,因此当程序终止时,流会自动为您关闭,但是不关闭流是不好的做法,因为在较大的运行时间较长的程序中,它们可能会导致问题,所以是的,一切都会正确关闭,但如前所述,它是不好的做法。
如果您一次必须打开多个流,它将因 outOfMemoryError 而崩溃,这是一个示例
public static void main(String[] args) {
LinkedList<Scanner> list = new LinkedList<>();
while(true)
list.add(new Scanner(System.in));
}
因此,如果您长时间不关闭流,则会导致此内存错误,还要注意此错误不是由于列表中的项目太多而引起的,这是由于流
编辑:
public static void main(String[] args) {
Scanner first = new Scanner(System.in);
Scanner second = new Scanner(System.in);
int x = first.nextInt();
int y = second.nextInt();
System.out.println("First scan returns: " + x);
System.out.println("Second scan returns: " + y);
first.close();
second.close();
}
如您所见,您可以打开多个 System.in 扫描仪,但是在读取变量时,您必须指定要使用的扫描仪对象。然而,这当然是毫无意义的,我想不出任何理由为什么您一次需要打开多个 System.in 扫描仪。