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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With