I am trying to select a human vs. human game, but the Null Pointer Exception happens whenever a human is involved.
What do I do to fix this?
// GameDriver.java
import java.util.Scanner;
public class GameDriver {
public static Board board;
public static void main(String[] args) {
Board board = new Board();
Scanner scan = new Scanner(System.in);
int playerX, playerO;
GamePlayer player1 = null; //****** THIS IS MY PROBLEM!!! HOW CAN I GET AROUND THIS?
GamePlayer player2 = null; // ***********************************************************
System.out.println("Select a number for who will be Player \"X\": \n1. Human Player \n2. Random Player \n3. Corner Player ");
playerX = scan.nextInt();
switch(playerX) {
case 1:
GamePlayer x = new GamePlayer('X');
player1 = x;
break;
case 2:
RandomPlayer r = new RandomPlayer('X');
player1 = r;
break;
case 3:
CornerPlayer c = new CornerPlayer('X');
player1 = c;
break;
default:
System.out.println("Error, please choose a value between 1 and 3:");
}
System.out.println("Select a number for who will be Player \"O\": \n1. Human Player \n2. Random Player \n3. Corner Player ");
playerO = scan.nextInt();
switch(playerO) {
case 1:
GamePlayer x = new GamePlayer('X');
player2 = x;
break;
case 2:
RandomPlayer r = new RandomPlayer('X');
player2 = r;
break;
case 3:
CornerPlayer c = new CornerPlayer('X');
player2 = c;
break;
default:
System.out.println("Error, please choose a value between 1 and 3:");
}
while(board.isFull() == false) {
player1.play();
board.toString();
if(board.checkWinner() == 'X')
System.out.println("Congratulations Player \"X\", you've won! Good game.");
player2.play();
board.toString();
if(board.checkWinner() == 'O')
System.out.println("Congratulations Player \"O\", you've won! Good game.");
if(board.isFull() == true && board.checkWinner() != 'X' && board.checkWinner() != 'O')
System.out.println("Draw. Please play another game.");
}
}
}
I don't know if this is necessary, but this is the program that controls the play interactions for the human player.
// GamePlayer.java
import java.util.Scanner;
public class GamePlayer{
protected char playerChar;
Scanner scan = new Scanner(System.in);
public GamePlayer (char playerChar) {
playerChar = this.playerChar;
}
public void play () {
System.out.println("Please enter the desired X-coordinate (0, 1, or 2) for the position.");
int row = scan.nextInt();
System.out.println("Please enter the desired Y-coordinate (0, 1, or 2) for the position.");
int col = scan.nextInt();
if(GameDriver.board.isOccupied(row, col) == false){
GameDriver.board.setPosition(row, col, playerChar);
}
else
System.out.println("Sorry, this spot is taken. Please select new coordinates. ");
Any help would be greatly appreciated!
The program compiles, but the board will not print because of this error, which occurs after the user selects the coordinates.

New Topic/Question
Reply




MultiQuote






|