HI all, I am trying to validate the input in my tic-tac-toe program. I had a good look around on the net and tried a few combinations, but I couldn't get anywhere. Some people seem to be using methods like hasNextInt(), some other a try and catch statement.
I tried first with a hasNextInt(), something like this:
while( !input.hasNextInt()){
System.out.print("This is not an int, please insert an int now");
input.nextInt();
}
So, here's the tic-tac-toe program and then I will explain where I inserted the supposed validation
http://ideone.com/wIk4mu
http://ideone.com/zZlIVa
SO this is the first validation attempt (I just added it for one input only but, if correct I will have to do it for both inputs):
if( !(myTicTacToe.isOdd( playerCounter ))){//player 1
System.out.println( "\nPlayer 1: enter the coordinates of the square.\nRow and column - values between 1 and 3." );
}
else{//player 2
System.out.println( "\nPlayer 2: enter the coordinates of the square.\nRow and column - values between 1 and 3." );
}
System.out.println( "\nRow and press enter: " );
rowInput = input.nextInt();
System.out.println( "\nColumn and press enter: " );
colInput = input.nextInt();
/*
while( !input.hasNextInt()){
System.out.print("This is not an int, please insert an int now");
input.nextInt();
}
*/
rowInput = myTicTacToe.optimizeInput( rowInput );//to subtract 1 from the input
colInput = myTicTacToe.optimizeInput( colInput );//to subtract 1 from the input
Then I tried with a try catch block. I have never used a try catch before, so I think I might have got a bit lost there.
if( !(myTicTacToe.isOdd( playerCounter ))){//player 1
System.out.println( "\nPlayer 1: enter the coordinates of the square.\nRow and column - values between 1 and 3." );
}
else{//player 2
System.out.println( "\nPlayer 2: enter the coordinates of the square.\nRow and column - values between 1 and 3." );
}
try {
System.out.println( "\nRow and press enter: " );
rowInput = input.nextInt();
System.out.println( "\nColumn and press enter: " );
colInput = input.nextInt();
}
catch (InputMismatchException e) {
System.out.println( "You need to enter an int " );
}
/*while( !rowInput.hasNextInt() )*/
rowInput = myTicTacToe.optimizeInput( rowInput );//to subtract 1 from the input
colInput = myTicTacToe.optimizeInput( colInput );//to subtract 1 from the input
I think I am doing something wrong there, can the try and catch statement handles two inputs like above or does each input need to have its own try and catch statement?
thanks