[java] tic tac toe issues

Started by
1 comment, last by grmokbel 12 years, 6 months ago
Hi I was wondering if someone could explain something to me.

in my Board class i declare a board object with the following constructor.(included class specific variables)

/**
* Class variables.
*/
final private int rows = 3; // number of rows
final private int columns = 3;
private String[][] board;
final private String unmarked = " "; // unmarked region on the game board.
/**
* Declares a two-dimensional array board then fills each index with blank spaces.
*/
public Board()
{
String[][] board = new String[rows][columns];
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
board[j] = unmarked;
}
}
}


but upon calling for move validation @ the moveValidator method
public boolean moveValidator(int r, int c)
{
int row = r - 1; // to account for the way the player reads the board we subtract 1 from row
int col = c - 1; // to account for the way the player reads the board we subtract 1 from column
if(board[row][col].equals(unmarked))
{
return true;
}
else
{
System.out.println("Cannot mark at location [" + r + "," + c + "]");
return false;
}

}


I am constantly given this error :

Exception in thread "main" java.lang.NullPointerException
at Board.moveValidator(Board.java:41)
at TicTacToe.main(TicTacToe.java:55)

Upon further reading it seems that if I call String.equals(object) and object is null it returns NullPointerException. [s]My problem seems to be(at least from what my untrained eyes see) that I am not actually filling the board array with blank spaces. [/s] (Just set up a tester class and found this is not the case.

If you have the time and you feel you could help that'd be great, I'm relatively new to programming(7 weeks in) but am thoroughly enjoying the challenges even a simple game like tic tac toe has posed.

I will probably run into more problems as I continue to test this cooky program. If you need to see the rest of my code I am more then willing to post it.
Advertisement
In your constructor you have declared a local variable named "board". If you remove the type from this statement it will be an assignment to the field, rather than a local declaration.

You should investigate your IDE/project settings and configure it to warn you about variable shadowing.

In your constructor you have declared a local variable named "board". If you remove the type from this statement it will be an assignment to the field, rather than a local declaration.

You should investigate your IDE/project settings and configure it to warn you about variable shadowing.


Rip-off thank you so much, that solved my problem, my program runs flawlessly.

I can't believe the coincidence though.. I stopped reading the book (my java programming book) to work on this side project on the same page as "Common Error: Shadowing".

This topic is closed to new replies.

Advertisement