我正在开发一款游戏,但我的扫描仪遇到了一些小问题。
我得到了一个从未关闭的资源泄漏扫描仪。
但我以为我的扫描仪之前可以工作而没有关闭它。
但现在不是了。有人可以帮我吗?
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).");
}
}
我假设您使用的是java 7,因此您会收到编译器警告,当您不关闭资源时,您通常应该在finally块中关闭扫描仪。
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
//rest of the code
}
finally {
if(scanner!=null)
scanner.close();
}
或者更好:使用新的尝试使用资源声明 http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html:
try(Scanner scanner = new Scanner(System.in)){
//rest of your code
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)