Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I do not close the Scanner?

Tags:

java

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.

like image 897
harrym Avatar asked Jan 10 '23 20:01

harrym


2 Answers

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.

like image 85
Nathan Hughes Avatar answered Jan 12 '23 08:01

Nathan Hughes


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.

like image 34
Nekojimi Avatar answered Jan 12 '23 08:01

Nekojimi