我正在开发游戏,我的扫描仪遇到了一些问题。 我从未关闭资源泄漏扫描程序。
但是我认为我的扫描仪在没有关闭之前就已经工作了。 但现在不是。有人可以帮帮我吗?
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).");
}
}
答案 0 :(得分:46)
我假设您使用的是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
}
答案 1 :(得分:5)
根据扫描程序的Javadoc,它会在您调用它的close方法时关闭流。一般来说,创建资源的代码也负责关闭它。 System.in不是由您的代码实例化的,而是由VM实例化的。因此,在这种情况下,不关闭扫描程序,忽略警告并添加注释为什么忽略它是安全的。如果需要,VM将负责关闭它。
(Offtopic:而不是“数量”,“数字”这个词更适合用于一些玩家。英语不是我的母语(我是荷兰语)而且我曾经犯过完全相同的错误。)
答案 2 :(得分:1)
以下是java for scanner
的更好用法try(Scanner sc = new Scanner(System.in)) {
//Use sc as you need
} catch (Exception e) {
// handle exception
}
答案 3 :(得分: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).");