Question

JAVA TIC TAC TOE - please help me correct my code Write a program that will...

JAVA TIC TAC TOE - please help me correct my code

Write a program that will allow two players to play a game of TIC TAC TOE.

  1. When the program starts, it will display a tic tac toe board as below

|    1       |   2        |   3

|    4       |   5        |   6

                |    7      |   8        |   9

  1. The program will assign X to Player 1, and O to Player    The program will ask Player 1, to select a position where they would like to mark.

Player will enter values 1-9.

For Example

When the game starts, if player 1 selects 2. The program will redraw the board with position 2 marked as X.

|    1       |   X        |   3

|    4       |   5        |   6

                |    7      |   8        |   9

                Player 2 enters 6, the boards is redrawn as below

|    1       |   X        |   3

|    4       |   5        | O

                |    7      |   8        |   9

  1. The program will alternate moves between Player 1 and Player 2 until the game is tied or won.

If the game is won, display the game winner, and ask the user if they want to play again. If yes, restart the game. If not quit the game.

  1. After each move, the board should be drawn to display the position where the move was marked.

  1. If a position is marked, X or O, the player is not allowed to select the same position again
  2. Winner
    1. Game is won if each row or each column has the same mark.
    2. Game is won if diagonal rows have the same mark.

You must create a class object called board with methods and attributes when implementing this game. All methods should be defined within the class object.

Error message I am getting after first input

Exception in thread "main" java.lang.NullPointerException
   at JavaProgramICards/ticTacToe.Board.checkSpace(Board.java:42)
   at JavaProgramICards/ticTacToe.Main.main(Main.java:27)


package ticTacToe;

public class Board {

   private static char[][] board;

   public void initBoard(char[][] board) {
       System.out.println("New Tic Tac Toe Board \n Good Luck!");
       int a = 1;
       for (int i = 0; i < 3; i++)
           for (int j = 0; j < 3; j++) {
               board[i][j] = (char) (a + '0');
               a++;
           }
   }

  
   public void printBoard(char[][] board) {
       for (int i = 0; i < 3; i++) {
           for (int j = 0; j < 3; j++) {
               System.out.print(" | " + board[i][j]);
           }
           System.out.print(" |\n");
       }

   }

   public boolean checkSpace(int space) {

       if (space > 0 && space <= 9) {
           int i = (space - 1) / 3;
           int j = (space - 1) % 3;

           if (board[i][j] == 'X' || board[i][j] == 'O')
               return false;
           else
               return true;
       }
       return false;

   }

   public void place(int space, char input) {
       int i = (space - 1) / 3;
       int j = (space - 1) % 3;
       board[i][j] = input;
   }

   public boolean isWinner() {

       for (int i = 0; i < 3; i++) {
           if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
               return true;

       }

       for (int j = 0; j < 3; j++) {
           if (board[0][j] == board[1][j] && board[1][j] == board[2][j])
               return true;

       }
       if ((board[0][0] == board[1][1] && board[1][1] == board[2][2])
               || (board[2][0] == board[1][1] && board[1][1] == board[0][2]))
           return true;

       else
           return false;

   }
}

package ticTacToe;

import java.util.Scanner;
import ticTacToe.Board;

class Main {
   public static void main(String[] args) {
       char[][] board2 = new char[3][3];
       Board board = new Board();
       Scanner scan = new Scanner(System.in);
       board.initBoard(board2);
       board.printBoard(board2);
       int turns = 0;
       while (true) {

           while (true) {
               System.out.print("Player 1: Enter your move (choose an available number 1-9) ");
               int space = scan.nextInt();
               if (board.checkSpace(space)) {
                   board.place(space, 'X');
                   board.printBoard(board2);
                   turns += 1;
                   break;
               } else {
                   System.out.println("There already is an X or O marker already there");
               }
           }
           if (board.isWinner()) {
               System.out.println("Woo, Player 1 Wins!");
               break;
           }
           if (turns == 9) {
               System.out.println("Awh it's a draw!");
               break;
           }

           while (true) {
               System.out.print("Player 2: Enter your move (choose an available number 1-9) ");
               int space = scan.nextInt();
               if (board.checkSpace(space)) {
                   board.place(space, 'O');
                   board.printBoard(board2);
                   turns += 1;
                   break;
               } else {
                   System.out.println("There already is an X or O marker already there");
               }
           }
           if (board.isWinner()) {
               System.out.println("Alright, alright alright! Player 2 wins!");
               break;
           }
       }

   }

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

thanks for the question, I have fixed the null pointer error but still the program was not working as expected, I have fine tuned the classes and its working as expected, please find the updated two classes.

thank you !

===============================================================================

package ticTacToe;

public class Board {
    private char[][] board;

    public Board() {

        char[][] temp = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
        board = temp;

    }

    public void initBoard(char[][] board) {
        System.out.println("New Tic Tac Toe Board \n Good Luck!");
        int a = 1;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++) {
                board[i][j] = (char) (a + '0');
                a++;
            }
    }

    public void printBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(" | " + board[i][j]);
            }
            System.out.println();

        }
    }

    public boolean checkSpace(int space) {
        if (space > 0 && space <= 9) {
            int i = (space - 1) / 3;
            int j = (space - 1) % 3;
            if (board[i][j] == 'X' || board[i][j] == 'O')
                return false;
            else
                return true
;
        }
        return false;
    }

    public void place(int space, char input) {
        int i = (space - 1) / 3;
        int j = (space - 1) % 3;
        board[i][j] = input;

    }

    public boolean isWinner() {
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && (board[i][0] == 'X' || board[i][0] == 'O')) {

                return true;
            }

        }
        for (int j = 0; j < 3; j++) {
            if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && (board[0][j] == 'X' || board[0][j] == 'O')) {

                return true;
            }

        }

      if ((board[0][0] == board[1][1] && board[1][1] == board[2][2] && (board[0][0] == 'X' || board[0][0] == 'O'))
                || (board[2][0] == board[1][1] && board[1][1] == board[0][2] && (board[2][0] == 'X' || board[2][0] == 'O'))) {

            return true;
        } else
            return false
;
    }
}

===============================================================================

package ticTacToe;

import java.util.Scanner;



class Main {

    public static void main(String[] args) {



        Board board = new Board();

        Scanner scan = new Scanner(System.in);



        board.printBoard();

        int turns = 0;

        while (true) {

            while (true) {

                System.out.print("Player 1: Enter your move (choose an available number 1-9) ");

                int space = scan.nextInt();

                if (board.checkSpace(space)) {

                    board.place(space, 'X');

                    board.printBoard();

                    turns += 1;

                    break;

                } else {

                    System.out.println("There already is an X or O marker already there");

                }

            }

            if (board.isWinner()) {

                System.out.println("Woo, Player 1 Wins!");

                break;

            }

            if (turns == 9) {

                System.out.println("Awh it's a draw!");

                break;

            }

            while (true) {

                System.out.print("Player 2: Enter your move (choose an available number 1-9) ");

                int space = scan.nextInt();

                if (board.checkSpace(space)) {

                    board.place(space, 'O');

                    board.printBoard();

                    turns += 1;

                    break;

                } else {

                    System.out.println("There already is an X or O marker already there");

                }

            }

            if (board.isWinner()) {

                System.out.println("Alright, alright alright! Player 2 wins!");

                break;

            }

        }

    }

}

===============================================================================

thanks a lot !

Add a comment
Know the answer?
Add Answer to:
JAVA TIC TAC TOE - please help me correct my code Write a program that will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can somebody help me with this coding the program allow 2 players play tic Tac Toe....

    Can somebody help me with this coding the program allow 2 players play tic Tac Toe. however, mine does not take a turn. after player 1 input the tow and column the program eliminated. I want this program run until find a winner. also can somebody add function 1 player vs computer mode as well? Thanks! >>>>>>>>>>>>>Main program >>>>>>>>>>>>>>>>>>>>>>> #include "myheader.h" int main() { const int NUM_ROWS = 3; const int NUM_COLS = 3; // Variables bool again; bool won;...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • In traditional Tic Tac Toe game, two players take turns to mark grids with noughts and...

    In traditional Tic Tac Toe game, two players take turns to mark grids with noughts and crosses on the 3 x 3 game board. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row in the game board wins the game. Super Tic Tac Toe game also has a 3 x 3 game board with super grid. Each super grid itself is a traditional Tic Tac Toe board. Winning a game of Tic...

  • In the C++ programming language write a program capable of playing 3D Tic-Tac-Toe against the user....

    In the C++ programming language write a program capable of playing 3D Tic-Tac-Toe against the user. Your program should use OOP concepts in its design. Use Inheritance to create a derived class from your Lab #9 Tic-Tac-Toe class. You can use ASCII art to generate and display the 3x3x3 playing board. The program should randomly decide who goes first computer or user. Your program should know and inform the user if an illegal move was made (cell already occupied). The...

  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • Hi, I am a student in college who is trying to make a tic tac toe...

    Hi, I am a student in college who is trying to make a tic tac toe game on Java. Basically, we have to make our own game, even ones that already exist, on Java. We also have to implement an interface, that I have no idea exactly. The professor also stated we need at least 2 different data structures and algorithms for the code. The professor said we could use code online, we'd just have to make some of our...

  • Tic-Tac-Toe (arrays and multidimensional arrays) C++ Write an interactive program that plays tic-tac-toe. Represent the board...

    Tic-Tac-Toe (arrays and multidimensional arrays) C++ Write an interactive program that plays tic-tac-toe. Represent the board as a 3 X 3 character array. Initialize the array to blanks and ask each player in turn to input a position. The first player's position is marked on the board with a O and the second player's position is marked with an X. Continue the process until a player wins or the game is a draw. To win, a player must have 3...

  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT