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.