2013-03-25 90 views
19

我正在开发一款游戏,并且遇到了扫描仪的一个小问题。 我得到一个永不关闭的资源泄漏扫描器。扫描仪从不关闭

但我认为我的扫描仪之前没有关闭它。 但现在不是。任何人都可以帮助我吗?

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 <= 0) || (amountOfPlayers > 2)); 
     System.out.println("You've selected " + amountOfPlayers+" player(s)."); 
    } 
} 
+2

一些更好的使用你怎么能告诉你的扫描仪无法工作了?你看到什么行为? – 2013-03-25 11:25:13

回答

36

我假设你使用的是Java 7,这样你就会得到一个编译器警告,当你不关闭资源应关闭扫描仪通常在finally块。

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

甚至更​​好:使用新的Try with resource statement

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

'新的扫描仪(System.in)'应该用'try-catch'块包围吗? – Maroun 2013-03-25 11:23:41

+0

@MarounMaroun不一定。但它是一个很好的做法,关闭你的资源在一个finally块内。 – PermGenError 2013-03-25 11:24:55

+1

谢谢,真的像Try with resource statement一样,就像一个魅力! – 2013-03-25 11:28:55

0

试试这个

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)."); 
4

根据扫描仪的Javadoc中,当你调用它的close方法关闭该流。一般来说,创建资源的代码也负责关闭它。 System.in没有被你的代码实例化,而是被虚拟机实例化。因此,在这种情况下,不要关闭扫描仪是安全的,忽略警告并添加评论为什么忽略它。如果需要,虚拟机将负责关闭它。 (Offtopic:而不是“金额”,“数字”这个词将更适合用于众多玩家。英语不是我的母语(我是荷兰人),我曾经做过完全一样的错误。)

1

这里是Java的扫描仪

try(Scanner sc = new Scanner(System.in)) { 

    //Use sc as you need 

} catch (Exception e) { 

     // handle exception 

}