Niek van der Linden Niek van der Linden - 5 months ago 72
Java Question

Scanner is never closed

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(;
int amountOfPlayers;
do {
System.out.print("Select the amount of players (1/2): ");
while (!scanner.hasNextInt()) {
System.out.println("That's not a number!");; // this is important!

amountOfPlayers = scanner.nextInt();
while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
System.out.println("You've selected " + amountOfPlayers+" player(s).");


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(;
    //rest of the code
finally {

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

try(Scanner scanner = new Scanner({
    //rest of your code