扫描仪永远不会关闭 [英] Scanner is never closed

查看:350
本文介绍了扫描仪永远不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a game and I came across a little problem with my scanner. I'm getting a resource leak scanner never closed.

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

But I thought my scanner was working before without closing it. But now it ain't. Anyone can help me out here?

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块中关闭扫描程序。

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

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

甚至更好:使用新的尝试使用资源声明

Or even better: use the new Try with resource statement:

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

这篇关于扫描仪永远不会关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆