4

I have a question about the Java's Scanner. I am writing a tic-tac-toe program, and this function gets called every time a player should make its move.

public void mossa(){
    int riga, colonna;
    int errore;
    Scanner input = new Scanner(System.in);
    if(player=='O')
        System.out.println("GIOCATORE O\n");
    else
        System.out.println("GIOCATORE X\n");

    do{
        errore = 0;
        System.out.println("Riga: ");
        riga = input.nextInt();

        System.out.println("Colonna: ");
        colonna = input.nextInt();

        if(board[riga][colonna]!=' '){
            errore=1;
            System.out.println("Hai scelto una casella gia occupata!\n");
        }
        if(riga>3 || colonna>3 || riga<0 ||colonna<0){
            errore=1;
            System.out.println("Hai scelto una casella che non esiste!\n");
        }

    }while(errore==1);

    //----->input.close();<------


    if(player == 'X')
        board[riga][colonna] = 'X';
    else
        board[riga][colonna] = 'O';

    togglePlayer();
}

At first I thought that it was better to close the Scanner after having captured the player's move, and then opening it again when the function gets called another time (see the input.close() commented). The problem is that if I close the scanner, I have a runtime error saying that the scanner is empty, and putting the nextInt() in an if driven by hasNextInt() doesn't help. So, is it wrong leaving the input Scanner not closed (I have only the warning of resource leak)?

Thank you in advance.

harrym
  • 121
  • 1
  • 9

3 Answers3

5

You don't have to close the Scanner. It's a wrapper around standard input, the JVM will take care of closing stdin for you when the program is terminated.

Static code analysis only detects that you have something closeable that you didn't close, so it complains. It's not paying attention to the thing that the Scanner is wrapping.

Things like files, network sockets, and jdbc objects need closing. stdin, stdout, and stderr get taken care of for you by the jvm, byteArray streams have nothing that needs closing. But Java uses a decorator pattern to wrap streams and the static analysis tool doesn't differentiate.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
3

I've never heard of anything saying that you should close a scanner while not expecting input, only that you should close them when your program is finished (and in theory, Java will close it for you anyway). I very much doubt that having a single scanner open will cause any kind of resource leakage.

Nekojimi
  • 118
  • 10
  • Thank you! Since I am switching from C to java, maybe I was thinking like "I need to do free() like when I program in C!" :) – harrym Sep 11 '14 at 14:43
1

Only close the scanner when you are finished using it. If you do not explicitly close the scanner eventually the garbage collector will destroy it and remove it from memory after your program is terminated.

brso05
  • 13,142
  • 2
  • 21
  • 40