Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: TicTacToe

  1. #1
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default TicTacToe

    Hello! I have this code here

    public class TicTacToe {
    	public static int row,col;
    	public static char[][] board = new char[3][3];
    	public static char turn = 'X';
     
    	public static void main(String[] args) {
    		for(int i = 0; i < 3; i++) {
    			for(int j = 0; j < 3; j++) {
    				board[i][j] = '_';
    			}
    		}
    		Play();
    	}
     
    	public static void printBoard() {
    	for(int i = 0; i < 3; i++) {
    		Out.println();
    		for(int j = 0; j < 3; j++) {
    			if(j == 0){
    				Out.print("| ");
    			}
    			Out.print(board[i][j] + " | ");
    		}
    	}
    	Out.println();
     
    }
     
     
    public static void Play() {
    	boolean playing = true;
    	printBoard();
    	Out.println();
    	int nOfTurns = 1;
    	Out.println("Turn: " + nOfTurns);
     
    	while(playing){
    		Out.println();
    		Out.println("Player:" +" "+ turn);
    		Out.print("Enter a row:");
    		row = In.readInt() -1;
    		Out.print("Enter a coloumn:");
    		col = In.readInt() -1;
    		board[row][col] = turn;
    		nOfTurns++;
    		Out.println();
    		Out.println("Turn: "+ nOfTurns);
    		if(GameOver(row,col)) {
    			playing = false;
    			Out.println("Player" +" "+turn +" "+"has won");
    		}
    		printBoard();
     
    		if(turn == 'X') {
    			turn = 'O';
    		}else{
    			turn = 'X';
    		}
    	}
    }
     
    public static boolean GameOver(int rowMove,int colMove) {
    	if(board[0][colMove] == board[1][colMove] && board[0][colMove] == board[2][colMove]){
    		return true;
    	}else if(board[rowMove][0] == board[rowMove][1] && board[rowMove][0] == board[rowMove][2]) {
    		return true;
    	}else if(board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_') {
    		return true;
    	}else if(board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_') {
    		return true;
    	}else
    		return false;
    }

    And it works fine.Now I want to implement a "safety" mechanicsm in the code.What I mean is I want to make sure that no wrong inputs (regarding rows and coloumns) can be made. So the range is from 1 - 3 and I want when the users puts in lets say 4, a message pops on on the screen saying that that is not a valid input. I want to execute this WITHOUT exceptions.I was thinking of creating a method (boolean) that will take an input compare it to a lower and upperbound and return true or false accordingly.My only issue is how will I implement that in the play method. Any help?

    Thanks!

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    loop
    ask for input
    get user input
    test user input
    if valid - exit loop
    else give error message and go to start of loop
    end loop
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    Hey, so do you mean to implement this as an "standalone" method or a part of a method?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    It could all be in a method.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    Okay i'll try and implement this in this play method, I'll let you know what happens.Thanks!

    --- Update ---

    Okay so I've tried a few things and this is what I have come up with;
    while(playing){
    		Out.println();
    		Out.println("Player:" +" "+ turn);
    		Out.print("Enter a row:");
    		row = In.readInt() -1;
    		if(row > 3 || row < 1) {
    			Out.println("Invalid input");
    		}
    		Out.print("Enter a coloumn:");
    		col = In.readInt() -1;
    		board[row][col] = turn;
    		nOfTurns++;
    		Out.println();
    		Out.println("Turn: "+ nOfTurns);
    		if(GameOver(row,col)) {
    			playing = false;
    			Out.println("Player" +" "+turn +" "+"has won");
    		}
    		printBoard();
     
    		if(turn == 'X') {
    			turn = 'O';
    		}else{
    			turn = 'X';
    		}
    	}
    }
    And i get an ArrayOutOfBoundIndex error, which excatly what I'm trying to avoid.What am I doing wrong on this loop?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    How does the simple if statement keep the invalid value from being used?
    Look at post#2. That code will stay in the loop until there is a valid value.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    Okay so Im not sure how to implement it in a single method, so I did it in two.
    public static int readNumber() {
    	boolean isValid = false;
    	int number;
    	do {	
     
    	number = In.readInt() - 1;
     
    	if (!In.done()) {
            Out.println("Invalid input");
            In.readLine(); 
          } else if (number < 1 || number > 3) {
            Out.println("Number must be between 1 and 3");
          } else {
            isValid = true;
          }
        } while (!isValid);
     
        return number;
      }
    }

    Now I'm kinda having issues with this if loop.What I mean is when I input 1 it prints out the message,although it shouldnt What am I missing?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    	number = In.readInt() - 1;
    What are the valid values that can be in number?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    1 2 3

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    To get 1,2,3 in number the user needs to enter: 2,3,4
    Look at this statement from the code:
    	number = In.readInt() - 1;   // map user input to 0 based index value

    The valid index values for a 3 dim array are: 0,1,2
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    Actually no, I have teste the code and it works just like intended.If I input 1 and 1 for row and coloumn the very top left field will be marked. Without reading in the Input that way you would have to use 0 1 2, to initialize the fields, meaning the very first field would be 0 0.Which kinda isnt so wanted and user friendly.PS I have fixed the issue

    public static int readNumber() {
    	boolean isValid = false;
    	int number;
    	do {	
     
    	number = In.readInt() - 1;
     
    	if (!In.done()) {
            Out.println("Invalid input");
            In.readLine(); 
          } else if (number < 0 || number > 3) {
            Out.println("Number must be between 1 and 3");
          } else {
            isValid = true;
          }
        } while (!isValid);
     
        return number;
      }
    }

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: TicTacToe

    What happens if the user enters 4?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Apr 2020
    Posts
    147
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe

    I havent tried it with 4, I'll check it

    --- Update ---

    Okay so it throws an ArrayOutOfBoundIndex Exception.Now it happens only for 4 I've tried numbers higher than 4,and it works fine.Why in the world is number 4 the problem?

    EDIT: So okay, I'm kinda making silly mistakes.Since I've written the input method with - 1 the values that need to be checked need to be adjusted.I've done it for one side of the loop but the the second.The code needs to look like this

    public static int readNumber() {
    	boolean isValid = false;
    	int number;
    	do {	
     
    	number = In.readInt() - 1;
     
    	if (!In.done()) {
            Out.println("Input must be a valid number");
            In.readLine(); 
          } else if (number < 0 || number > 2) {
            Out.println("The number is not in the specified range: 1-3");
          } else {
            isValid = true;
          }
        } while (!isValid);
     
        return number;
      }
    }
    Last edited by arhzz; June 5th, 2020 at 04:42 PM.

Similar Threads

  1. TicTacToe error
    By monikathelover1999 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: September 24th, 2019, 03:52 PM
  2. Tictactoe with out GUI
    By Andile in forum Java Theory & Questions
    Replies: 2
    Last Post: September 15th, 2012, 03:49 PM
  3. TicTacToe 2D Array help
    By steel55677 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: July 9th, 2011, 05:01 PM
  4. TicTacToe
    By Zerro900 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 27th, 2011, 08:29 AM
  5. Tictactoe problem
    By Nostromo in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 26th, 2011, 03:38 PM