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

Recommended Answers

All 23 Replies

you are reading int input and are treating it as booleans. that's not how it works.
// about your first attempt.
for the rest.
.. we don't know what you pass as parameter, so how would we know what's going on?

Start with one simple validation, get it working, then repeat that pattern.
Here's a typical pattern for inputting one value and validating it, with an initial prompt, and a different re-prompt after errors:

display normal request for input
while (true) {
   get user input
   if (user cancelled) exit program // give user a way out if they can't get input right
   validate user input
   if (input is valid) break;
   display error message/re-prompt for input
}

the "validate user input" may involve catching an exception, but you can handle that right there and generate an error message, so the structure remains simple.

thanks guys.

you are reading int input and are treating it as booleans. that's not how it works.

What do you mean by that? input is a Scanner type and I would have thought any variable could be tested with hasNextInt() because that function returns true or false.

Start with one simple validation, get it working, then repeat that pattern.

I am following your structure, but I wonder, is there a method (I couldn't find one and I had a look on the net quite a bit now trying to understand how validating an int is achieved) that returns true if an input is a int and false if it isn't?

thanks

You could read the user's input as a String, then try to parse it and catch any exception something like this

read input
try {
   intVar = Integer.valueOf(input);
   valid = true; // if we get here the string was parsed OK
} catch NumberFormatException {
   valid = false
}

thanks, I this this is one of the things I don't understand about validating data, the fact that I have to have it inserted in a different format (a string) to validate it as an input. By all means, if this is the way to go then so be it. But I am kind of wondering then, if I go with this solution, then I have to make sure the string is actually converted to an integer before I make use of it (in the program in questions the inputs - row and column - are passed as integers to the methods)

That's right. In my pseudo code there's a boolean "valid" that is set to tell you if the int value if OK or not. You would then wrap that whole thing inside a loop like the one I posted earlier and keep looping/prompting/inputting/parsing until the boolean tells you the input was ok and the int value is ok to use.
There may be slicker ways to do it, but this pattern is very general, and can be used for inputting booleans, or chars that must be one of a small set, or requiring int values to be in a specified range etc etc

First result on Google

public static boolean isInteger(String s) 
{
    try 
    { 
        Integer.parseInt(s); 
    } 
    catch(NumberFormatException e) 
    { 
        return false; 
    }
    return true;
}

Use this and it will return true or false depending...

hi all sorry for the delay in posting back. Thanks for the suggestions. I have tried to gather them all together and come up with something. Here it is.
Basically I have added a function in my TicTacToe.java file:

//validation 
    public static boolean isInteger(String s){
        try{ 
            Integer.parseInt(s); 
        } 
        catch(NumberFormatException e){ 
            return false; 
        }
        return true;
    }//end of validation

And in the TicTacToeTest.java instead I changed the code slightly:
1) the two integer values rowInput and colInput are no of type String
2)I have changed input.nextInt() to input.next() (I have read somewhere that this method allows the user to input just one word - in my case a string '1', '2' or '3' - and discard the white space)
3)validated the two inputs separately. Here's the code:

    ...
    String rowInput;
    String colInput;
    ...

    System.out.println( "\nRow and press enter: " );
    rowInput = input.next();
    //validation row
    while( !(myTicTacToe.isInteger( rowInput )) || (( rowInput < 1 ) || ( rowInput > 3 )){
        System.out.println("\n The input has to be a number between 1 and 3, try again");
        rowInput = input.next();
    }
    //end of validation row     

    System.out.println( "\nColumn and press enter: " );
    colInput = input.next();
    //validation column
    while( !(myTicTacToe.isInteger( colInput )) || (( colInput < 1 ) || ( colInput > 3 )){
        System.out.println("\n The input has to be a number between 1 and 3, try again");
        colInput = input.next();
    }

If you want to see two files here they are:
http://ideone.com/WrRKR3
http://ideone.com/q1HzOq

Any feedback as usual much appreciated of course, thanks

Did you compile this? rowInput < 1 may not work too well when rowInput is a String!

I actually haven't compiled it no sorry, I thought I'd get your opinion on the logic first. When I coded the validation, my assumption was that in here while( !(myTicTacToe.isInteger( rowInput )) || (( rowInput < 1 ) || ( rowInput > 3 )){ when I called the method with a string parameter, the string would be converted into a int ( inside isInteger() with this try{ Integer.parseInt(s); } ) therefore it would have been safe enough for me to say something like rowInput < 1. I take my assumption was wrong?

Nothing you can do will ever turn a String into an int. Integer.parseInt(s) returns a new int value that you have to assign to a variable.
ps: Please do run your code thorugh the compiler if possible before posting it, otherwize people may spend a lot of time manually finding an error that the compiler would have diagnosed instamtly.

Right, done some validation, yay. The thing is it doesn't work. I compiled the program and the first time I got 6 errors, realizing that I did something silly. SO now I get only 2 errors. Let's have a look at the code.
in my TicTacToeTest.java I have this:

            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number
            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number

and in the TicTacToe.java I have the 2 methods (sorry I tried to use only one method, it makes more sense doesn't it? but it was a bit difficult to find a way to say to the method, if it's a row then print 'Row and press enter or type exit to leave the program' and if it's a column print 'Col and press enter or type exit to leave the program'). Sorry been a long day today!

//validation row
    public int getRowNumber( Scanner scanner ){
        int rowNumber;
        System.out.println( "\nRow and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ("exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                rowNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( rowNumber >= 1 ) && ( rowNumber <= 3 )){
                    return rowNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter row number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getRowNumber()

    //validation col
    public int getColNumber( Scanner scanner ){
        int colNumber;
        System.out.println( "\nCol and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ( "exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                colNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( colNumber >= 1 ) && ( colNumber <= 3 )){
                    return colNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter col number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getColNumber()

When I compile the program I get 2 errors here's the console message:

antobbo@antobbo-xps17-ubuntu:~/Documents/dell xps/My documents/java/tests/tictactoe1$ javac *.java
TicTacToe.java:115: error: cannot find symbol
    public int getRowNumber( Scanner scanner ){
                             ^
  symbol:   class Scanner
  location: class TicTacToe
TicTacToe.java:137: error: cannot find symbol
    public int getColNumber( Scanner scanner ){
                             ^
  symbol:   class Scanner
  location: class TicTacToe
2 errors

Now, I was a bit confused to be honest because I declared a new scanner object in my TicTacToeTest.java file like so:
Scanner input = new Scanner( System.in ); (that's why I pass the variable input of type scanner to the validating methos). I looked into it, and somebody in a forum claims that you just can't pass a variable of type scanner as a parameter. Unfortunately he doestn't say what the alternative is. Is it true I can't pass such a variable as parameter? Why?

thanks

If you need to see all the files here they are:
http://ideone.com/Gc0PvP
http://ideone.com/DJquda

You can pass anything as a parameter, including a Scanner. That looks like a good thing to do here. Your error message is a bit of a mystery to me.
Have you declared a variable or method called Scanner anywhere? Did you put the method declaration somewhere it shouldn't be? Do you have the necessary include statement for Scanner at the start of that file? Have you tried
public int getRowNumber( java.util.Scanner scanner ){ ...

James: my guess is you meant the import statement. missing that would be my guess as well.

Sorry yes, typo, "import" not "include"
(A good example of why not to use an IDE - I can't remember the last time I actually typed an import myself)

ah ok, well good to know I can pass a variable of type scanner. I added the link to the online compiler thinking it might be easier, sorry maybe I was wrond. ANyway, let's see what I have done in more details then. The scanner import declaration is in my TicTacToeTest.java, together with the call to the validating method, see below excerpt:

/*TicTacToeTest.java*/
import java.util.Scanner;

public class TicTacToeTest{

    public static void main( String[] args ){
    boolean isFull = false;//if true all the squares have been assigned.
    boolean isDraw = false;//to check if the game is draw
    boolean squareIsFull = false;//returns the status of a square, if false the square is full if true the square is empty
    boolean victory = false;//if returns true one of the players has won
    int playerCounter = 1;//if it is odd it's player1's turn if even it's player2's turn
    int rowInput;
    int colInput;
        Scanner input = new Scanner( System.in );
        TicTacToe myTicTacToe = new TicTacToe();//create object
        myTicTacToe.printBoard();
        while( !isFull ){
            isDraw = myTicTacToe.isDraw();
            if( isDraw ){
                System.out.println( "The game is draw!\n" );
                //print board
                //myTicTacToe.printBoard();
                break;
            }
            //print board
            //myTicTacToe.printBoard();
            //System.out.println("the number is " + playerCounter );
            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." );
            }

            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number
            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number...

The calls to the validating functions

rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number
            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number

pass the variable input of type Scanner to the validating function below, which is instead in a separate file, TicTacToe.java:

//validation row
    public int getRowNumber( Scanner scanner ){
        int rowNumber;
        System.out.println( "\nRow and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ("exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                rowNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( rowNumber >= 1 ) && ( rowNumber <= 3 )){
                    return rowNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter row number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getRowNumber()

    //validation col
    public int getColNumber( Scanner scanner ){
        int colNumber;
        System.out.println( "\nCol and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ( "exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                colNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( colNumber >= 1 ) && ( colNumber <= 3 )){
                    return colNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter col number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getColNumber()

So, even if the variable of type Scanner is created in one file, I am sure it is ok to use it in the other one..or am I missing something absolutely obvious here?!

You need the import statement in every file where you refer to the class.
ps You have two class to getRowNumber - pesumably one should be getColNumber?

Ok hang on, apparently the inport declaration needs to be in 2 places, both files. My bad. I thought the import declaration should have been used only where the Scanner variable is declared which is in my case TicTacToeTest.java. Clearly not. It works now, thanks guys for all your invaluable help as usual.
Here are the two files if anybody ever needs to use them and play around with them or whatever:

/*TicTacToe.java*/
import java.util.Scanner;
public class TicTacToe{ 
    //private boolean isFull = false;//if true all the squares have been assigned.
    //private int playerCounter = 1;//if it is odd it's player1's turn if even it's player2's turn
    private TicTacToeEn[][] board = new TicTacToeEn[3][3];//to represent the 3-by-3 board

    //private boolean isDraw;//to check if the game is draw
    //private boolean squareStatus;//returns the status of a square, if false the square is full if true the square is empty
    //private boolean victory;//if returns true one of the players has won  
    //private int row;//row of the 3-by-3 board
    //private int column;//column of the 3-by-3 board   
    //private int gameCounter;//counts the moves


    public enum TicTacToeEn{
        X, O, EMPTY 
    }//end of enum
    TicTacToeEn theSymbol;//of type enum holds the current theSymbol, X or O 
    //constructor
    public TicTacToe(){
        for( int i = 0; i < board.length; i++ ){
            for( int j = 0; j < board[i].length; j++ ){
                board[i][j] = TicTacToeEn.EMPTY;
            }//columns
        }//rows         
    }//end of constructor

    //checks if square is empty
    public boolean checkSquare( int row, int column ){
        if(board[row][column] == TicTacToeEn.EMPTY){
            return false;
        }
        else{
            return true;
        }       
    }//end of checkSquare()

    //assigns X or O to the square
    public void assignSymbol( int row, int column, int counter ){
        if( isOdd( counter )){//it's player1
            board[row][column] = TicTacToeEn.X;     
        }
        else{//it's player2
            board[row][column] = TicTacToeEn.O;     
        }
    }//end of assignSymbol()

    //check if the game is draw
    public boolean isDraw(){
        for( int i = 0; i < board.length; i++ ){
            for(int j = 0; j < board[i].length; j++ ){
                if( board[i][j] == TicTacToeEn.EMPTY ){//if there is an empty square
                    return false;
                }               
            }//end of column array
        }//end of row array
        return true;//if there isn't an empty square
    }//end of isDraw()

    //checks if anybody has won the game
    public boolean checkVictory( int row, int column, int counter ){
        if( isOdd( counter )){//it's player1
            theSymbol = TicTacToeEn.X;
        }
        else{//it's player2
            theSymbol = TicTacToeEn.O;
        }
        //determine victory
        if( 
            ( board[row][0] == theSymbol && board[row][1] == theSymbol &&   board[row][2] == theSymbol )//check 3-in-the-row horizontally   
            ||  ( board[0][column] == theSymbol && board[1][column] == theSymbol && board[2][column] == theSymbol )//check 3-in-the-row vertically          
            ||  ( board[0][0] == theSymbol && board[1][1] == theSymbol && board[2][2] == theSymbol )//check 3-in-the-row 1st diagonal           
            ||  ( board[0][2] == theSymbol && board[1][1] == theSymbol && board[2][0] == theSymbol )//check 3-in-the-row 2nd diagonal
        ){
            return true;
        }

        else{
            return false;
        }       
    }//end of checkVictory()

    //determine if the argument is odd or even
    public boolean isOdd( int number){
        if( number % 2 == 0){//it's even
            return true;
        }
        else{//it's odd
            return false;
        }
    }//end of isOdd()

    /*get the right input for the array, 
    effectively subtracting 1 to the input so that the 
    index is still within the array range*/
    public int optimizeInput( int theInput ){
            int newInput = theInput - 1;
            return newInput;
    }

    //print board
    public void printBoard(){
/*      System.out.print("\n\n\n\n\n");
        System.out.println("|   " + board[0][0] + "   |   " + board[0][1] + "   |   " + board[0][2] + "   |");
        System.out.println("|   " + board[1][0] + "   |   " + board[1][1] + "   |   " + board[1][2] + "   |");
        System.out.println("|   " + board[2][0] + "   |   " + board[2][1] + "   |   " + board[2][2] + "   |");
        System.out.print("\n\n\n\n\n"); */
        System.out.print("\n\n\n\n\n");
        System.out.printf("| %6s | %6s | %6s |", board[0][0], board[0][1], board[0][2]);
        System.out.printf("\n| %6s | %6s | %6s |", board[1][0], board[1][1], board[1][2]);
        System.out.printf("\n| %6s | %6s | %6s |", board[2][0], board[2][1], board[2][2]);
        System.out.print("\n\n\n\n\n");
    }
    //validation row
    public int getRowNumber( Scanner scanner ){
        int rowNumber;
        System.out.println( "\nRow and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ("exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                rowNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( rowNumber >= 1 ) && ( rowNumber <= 3 )){
                    return rowNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter row number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getRowNumber()

    //validation col
    public int getColNumber( Scanner scanner ){
        int colNumber;
        System.out.println( "\nCol and press enter or type exit to leave the program: " );
        while( true ){
            String userInput = scanner.next();
            if ( "exit".equalsIgnoreCase( userInput )){
                System.exit(1);//if users types exit, program terminates
            }

            try{
                colNumber = Integer.valueOf( userInput ); // goes straight to catch if input not numeric
                if (( colNumber >= 1 ) && ( colNumber <= 3 )){
                    return colNumber; // input was valid
                }
            }                
            catch( Exception e ){
                System.out.println( "\nRe-enter col number, must be an integer value, or  exit  to quit program" );
            }
        }//end while        
    }//end method getColNumber()

}//end of class

and the othe file:

/*TicTacToeTest.java*/
import java.util.Scanner;

public class TicTacToeTest{

    public static void main( String[] args ){
    boolean isFull = false;//if true all the squares have been assigned.
    boolean isDraw = false;//to check if the game is draw
    boolean squareIsFull = false;//returns the status of a square, if false the square is full if true the square is empty
    boolean victory = false;//if returns true one of the players has won
    int playerCounter = 1;//if it is odd it's player1's turn if even it's player2's turn
    int rowInput;
    int colInput;
        Scanner input = new Scanner( System.in );
        TicTacToe myTicTacToe = new TicTacToe();//create object
        myTicTacToe.printBoard();
        while( !isFull ){
            isDraw = myTicTacToe.isDraw();
            if( isDraw ){
                System.out.println( "The game is draw!\n" );
                //print board
                //myTicTacToe.printBoard();
                break;
            }
            //print board
            //myTicTacToe.printBoard();
            //System.out.println("the number is " + playerCounter );
            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." );
            }

            rowInput = myTicTacToe.getRowNumber( input ); // getRowNumber will always return a valid row number
            colInput = myTicTacToe.getColNumber( input ); // getRowNumber will always return a valid row number

/*          //validation row
            System.out.println( "\nRow and press enter: " );
            rowInput = input.next();
            while( !(myTicTacToe.isInteger( rowInput )) || (( rowInput < 1 ) || ( rowInput > 3 )){
                System.out.println("\n The input has to be a number between 1 and 3, try again");
                rowInput = input.next();
            }
            //end of validation row     

            System.out.println( "\nColumn and press enter: " );
            colInput = input.next();
            //validation column
            while( !(myTicTacToe.isInteger( colInput )) || (( colInput < 1 ) || ( colInput > 3 )){
                System.out.println("\n The input has to be a number between 1 and 3, try again");
                colInput = input.next();
            }
            //end of validation column   
*/

            rowInput = myTicTacToe.optimizeInput( rowInput );//to subtract 1 from the input
            colInput = myTicTacToe.optimizeInput( colInput );//to subtract 1 from the input

            //check input
            squareIsFull = myTicTacToe.checkSquare( rowInput, colInput );
            //if the square is taken - true - input again row and column till you find a free one
            while( squareIsFull ){
                System.out.println( "Square taken, try again. \nEnter the coordinates of the square.\nRow and column - values between 1 and 3." );
                System.out.println( "\nRow: " );
                rowInput = input.nextInt();
                System.out.println( "\nColumn: " );
                colInput = input.nextInt();
                rowInput = myTicTacToe.optimizeInput( rowInput );//to subtract 1 from the input
                colInput = myTicTacToe.optimizeInput( colInput );//to subtract 1 from the input
                //check input
                squareIsFull = myTicTacToe.checkSquare( rowInput, colInput );
            }
            //assign the symbol to the chosen square
            myTicTacToe.assignSymbol( rowInput, colInput, playerCounter );
            //print board
            myTicTacToe.printBoard();
            //check for draw
            victory = myTicTacToe.checkVictory( rowInput, colInput, playerCounter );
            //player 1
            if(( victory ) && ( myTicTacToe.isOdd( playerCounter ) )){
                System.out.println( " Player 1 wins!" );
                //print board
                //myTicTacToe.printBoard();
                break;
            }
            //player2
            else if(( victory ) && !( myTicTacToe.isOdd( playerCounter ) )){
                System.out.println( " Player 2 wins!" );
                //print board
                myTicTacToe.printBoard();
                break;
            }           
            playerCounter++;//increment counter to change player's turn
        }//end while loop
    }//end main 
}//end TicTacToeTest class

Excellent!

ps: The rule for imports is that if you want to say "Scanner" rather than "java.util.Scanner" anywhere then you need the import at the head of that file. The reason is more obvious for cases where the name is ambiguous, eg Timer. If you say
void myMethod(Timer t) {...
is that a java.util.Timer or a javax.swing.Timer? The fact that you happened to declare a java.util.Timer in some other file doesn't help.

Hi thanks, yes I was aware of that rule (the import rule lets you write 'the short form'). In my case though, I didn't realize that the import rule import java.util.Scanner; had to be in 2 places, I have always thought that the file where I declare the new variable of type Scanner was the only one that had to have the declaration, even if the Scanner variable was used somewhere else, because the new objects is created once, if that makes sense. So, as an example, in my case because this Scanner input = new Scanner( System.in ); is in my TicTacToeTest.java I thought that's where the import declaration had to be, even if the input variable is used in a different file the new object has been created once. Does it make sense?

That does make sense, but only because it's one very specific case. The langauge/compiler have to be designed for all the other more complicated cases.
Suppose, for example, that you wrote and compiled the class with the validation methods and put that in a jar and added it to your classpath. Then, later, you wrote the class that calls that method. When the compiler was compiling the method your Scanner variable didn't exist, you hadn't even started that code yet.
ps It's also misleading to think of the Scanner variable as being used in the validation method. It's not. Java calls by value, so it's a copy of the value of that variable that is created for the validation method.

I tried to use only one method, it makes more sense doesn't it? but it was a bit difficult to find a way to say to the method, if it's a row then print 'Row and press enter or type exit to leave the program' and if it's a column print 'Col and ...

Yes you're right, one method would make more sense. Once you spot duplucated code like that your first instinct is to generalise it. You could generalise what you have quite a lot like this, for example:

int getValidatedInt(String name, int min, int max, Scanner in) {
     print "Please enter value for " + name;
     ...
     validate input is an integer 
     ...
     if (num < min || num > max) print "enter a value for " + name + " between "+ min + " and " + max
     ...

Then call it like

int row = getValidatedInt("row", 1, 3, input);

ah great idea passing the string, didn't occur to me at all!
Cool right, thanks for all your help, I will close the thread now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.