fix this error: Exception in thread main java.lang.NullPointerException : Cannot read the array length because tictactoegame.TicTacToeGame.gameboard is null at TicTacToeGame/tictactoegame.TicTacToeGame.displayBoard( TicTacToeGame.java:18 ) at TicTacToeGame/tictactoegame.TicTacToeGame.main( TicTacToeGame.java:49
fix this error:
"Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "tictactoegame.TicTacToeGame.gameboard" is null
at TicTacToeGame/tictactoegame.TicTacToeGame.displayBoard(TicTacToeGame.java:18)
at TicTacToeGame/tictactoegame.TicTacToeGame.main(TicTacToeGame.java:49)"
package tictactoegame;
public class TicTacToeGame {
static int[][] gameboard;
static final int EMPTY = 0;
static final int NOUGHT = -1;
static final int CROSS = 1;
/* Set a square on the board must be empty */
public static void set(int val, int row, int col) throws IllegalArgumentException {
if (gameboard[row][col] == EMPTY)
gameboard[row][col] = val;
else throw new IllegalArgumentException("Player already there!");
}
/* display the board */
public static void displayBoard() {
for(int r=0; r<gameboard.length; r++) {
System.out.print("|");
for (int c=0; c<gameboard[r].length; c++) {
switch(gameboard[r][c]) {
case NOUGHT:
System.out.print("O wins" );
break;
case CROSS:
System.out.print("Xwins" );
break;
default: // EMPTY
System.out.println("");
}
System.out.print("|");
}
System.out.println();
}}
public static void createBoard(int rows, int cols) {
//TODO Initialize the gameboard
}
public static void winOrTie() {
//TODO Determine whether X or O won or there is a tie
}
public static void main(String[] args){
createBoard(3,3);
int turn = 0;
int playerVal;
int outcome;
try(java.util.Scanner Scan= new java.util.Scanner(System.in)){;
do {
displayBoard();
playerVal = (turn % 2 == 0)? NOUGHT : CROSS;
if (playerVal == NOUGHT)
System.out.println (" O's turn");
else System.out.println(" X's turn" );
System.out.print("Enter row and column:" );
try {
set(playerVal, Scan.nextInt(), Scan.nextInt());
} catch (Exception ex)
{System.err.println(ex); turn--;}
turn ++;
outcome = NOUGHT;
}
while ( outcome == -2 );
displayBoard();
switch (outcome) {
case NOUGHT:
System.out.println("O wins!");
break;
case CROSS:
System.out.println("X wins!");
break;
case 0:
System.out.println("Tie.");
break;
}
}}}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started