I am making a tic-tac-toe game in Java to review some Java concepts and practice OOP. So far I have 4 classes: Board
, Player
, Coordinate
, and Game
. I am having problems testing the Board
class. A board consists of an array of coordinates. There are currently two different constructor for Board
. The constructor that takes a single Coordinate
was mainly made for testing purposes.
Board.java
public class Board {
private Coordinate squares;
private Coordinate[] coordinateSet;
public Board(Coordinate squares) {
this.squares = squares;
}
public Board(Coordinate[] coordinateSet) {
this.coordinateSet = coordinateSet;
}
public Coordinate getSquares() {
return squares;
}
public Coordinate[] getCoordinates() {
return coordinateSet;
}
public Coordinate getCoordinate(int i) {
return coordinateSet[i];
}
}
Coordinate.java
public class Coordinate {
private int x;
private int y;
private int xFlag; // 0 if available, 1 if not available
private int yFlag; // 0 if available, 1 if not available
private boolean squareAvailability;
public Coordinate(int x, int y, int xFlag, int yFlag) {
this.x = x;
this.y = y;
this.xFlag = xFlag;
this.yFlag = yFlag;
}
public int getXCoordinate() {
return x;
}
public int getYCoordinate() {
return y;
}
public int getXFlag() {
return xFlag;
}
public int getYFlag() {
return yFlag;
}
public void setXFlag() {
if(xFlag == 0) {
xFlag = 1;
} else { }
}
public void setYFlag() {
if(yFlag == 0) {
yFlag = 1;
} else { }
}
public void add(Coordinate coordinate) {
// TODO Auto-generated method stub
}
public boolean isSquareAvailable(Coordinate coordinate) {
if(coordinate.getXFlag() == 0) {
if(coordinate.getYFlag() == 0) {
squareAvailability = true;
} else {
squareAvailability = false;
}
} else {
squareAvailability = false;
}
return squareAvailability;
}
}
BoardTest.java
import edu.learning.tictactoe.Board;
import edu.learning.tictactoe.Coordinate;
public class BoardTest {
public static void main(String[] args) {
Coordinate[] coordinates = new Coordinate[9];
Coordinate coordinate = new Coordinate(0, 0, 0, 0);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
coordinates[i + j] = new Coordinate(i, j, 0, 0);
}
}
Board board = new Board(coordinate);
System.out.println(board.getSquares().getXCoordinate());
Board board2 = new Board(coordinates);
System.out.println(board2.getCoordinates().getCoordinate(0).getXCoordinate()); // error
}
}
I get an error on the last line of BoardTest.java
in my IDE that I Cannot invoke getCoordinate(int) on the array type Coordinate[]
. The problem is that I am trying to return a Coordinate
object from an array of Coordinate
objects, which isn't possible(?) So how would I return a Coordinate
from an array of Coordinate
s?
board.getCoordinates()
returns an array and the compiler error tells you that this array does not have a method getCoordinate(int)
.
Simply write
board.getCoordinate(0).getXCoordinate()
if you want to access the coordinate via the array you could write
board.getCoordinates()[0].getXCoordinate()