扫描仪永远不会关闭

我正在开发一款游戏,我的扫描仪遇到了一些问题。 我的资源泄漏扫描仪从未关闭。

但我以为我的扫描仪在没有关闭它之前就已经工作了。 但现在不是。 有人可以帮帮我吗?

import java.util.Scanner; public class Main { public static final boolean CHEAT = true; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amountOfPlayers; do { System.out.print("Select the amount of players (1/2): "); while (!scanner.hasNextInt()) { System.out.println("That's not a number!"); scanner.next(); // this is important! } amountOfPlayers = scanner.nextInt(); while ((amountOfPlayers  2)); System.out.println("You've selected " + amountOfPlayers+" player(s)."); } } 

我假设您使用的是java 7,因此您会收到编译器警告,当您不关闭资源时,您应该通常在finally块中关闭扫描程序。

 Scanner scanner = null; try { scanner = new Scanner(System.in); //rest of the code } finally { if(scanner!=null) scanner.close(); } 

甚至更好:使用新的Try with资源语句

 try(Scanner scanner = new Scanner(System.in)){ //rest of your code } 

根据扫描程序的Javadoc,它会在您调用它的关闭方法时关闭流。 一般来说,创建资源的代码也负责关闭它。 System.in没有由您的代码实例化,而是由VM实例化。 因此,在这种情况下,不关闭扫描仪是安全的,忽略警告并添加注释为什么忽略它。 如果需要,VM将负责关闭它。

(Offtopic:而不是“数量”,“数字”这个词更适合用于一些玩家。英语不是我的母语(我是荷兰语),我曾经犯过完全相同的错误。)

这里有一些更好的java用于扫描仪的用法

 try(Scanner sc = new Scanner(System.in)) { //Use sc as you need } catch (Exception e) { // handle exception } 

尝试这个

 Scanner scanner = new Scanner(System.in); int amountOfPlayers; do { System.out.print("Select the amount of players (1/2): "); while (!scanner.hasNextInt()) { System.out.println("That's not a number!"); scanner.next(); // this is important! } amountOfPlayers = scanner.nextInt(); } while ((amountOfPlayers <= 0) || (amountOfPlayers > 2)); if(scanner != null) { scanner.close(); } System.out.println("You've selected " + amountOfPlayers+" player(s).");