I have a question about Java scanner. I am writing a tic-tac-toe program, and this function is called every time a player has to make his 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);
if(player == 'X')
board[riga][colonna] = 'X';
else
board[riga][colonna] = 'O';
togglePlayer();
}
At first I thought it was better to close the Scanner after it captured the player’s movement, and then open it again when the function is called at another time (see comment input.close ()). The problem is that if I close the scanner, I got a runtime error saying that the scanner is empty, and including nextInt () in the if called by hasNextInt () does not help. So, is it wrong to leave the input? The scanner is not closed (I only have a warning about a resource leak)?Thanks in advance.
source
share