Scanner is never closed

前端 未结 4 1775
渐次进展
渐次进展 2020-12-01 10:34

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 be

相关标签:
4条回答
  • 2020-12-01 11:12

    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
    }
    
    0 讨论(0)
  • 2020-12-01 11:14

    Try this

    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).");
    
    0 讨论(0)
  • 2020-12-01 11:16

    According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

    (Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

    0 讨论(0)
  • 2020-12-01 11:18

    Here is some better usage of java for scanner

    try(Scanner sc = new Scanner(System.in)) {
    
        //Use sc as you need
    
    } catch (Exception e) {
    
            //  handle exception
    
    }
    
    0 讨论(0)
提交回复
热议问题