Okay, I'll see what I can do
EDIT: Didnt help, maybe I got it wrong?
public class TicTacToe {
public static int row,col;
public static char[][] board = new char[3][3];
public static char turn = 'X';
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static void printBoard() {
for(int i = 0; i < 3; i++) {
Out.println();
for(int j = 0; j < 3; j++) {
if(j == 0){
Out.print("| ");
}
Out.print(board[i][j] + " | ");
}
}
Out.println();
}
public static void Play() {
boolean playing = true;
printBoard();
Out.println();
int nOfTurns = 1;
Out.println("Turn: " + nOfTurns);
while(playing){
Out.println();
Out.println("Player:" +" "+ turn);
Out.print("Enter a row:");
row = readNumber();
Out.print("Enter a coloumn:");
col = readNumber();
do {
if(isTaken(row,col)) {
Out.println("That cell is taken,please enter another cell");
row = readNumber();
col = readNumber();
}
}while(!isTaken(row,col));
board[row][col] = turn;
nOfTurns++;
Out.println();
Out.println("Turn: "+ nOfTurns);
if(GameOver(row,col)) {
playing = false;
Out.println("Player" +" "+turn +" "+"has won!");
}
printBoard();
if(turn == 'X') {
turn = 'O';
}else{
turn = 'X';
}
}
}
public static boolean GameOver(int rowMove,int colMove) {
if(board[0][colMove] == board[1][colMove] && board[0][colMove] == board[2][colMove]){
return true;
}else if(board[rowMove][0] == board[rowMove][1] && board[rowMove][0] == board[rowMove][2]) {
return true;
}else if(board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_') {
return true;
}else if(board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_') {
return true;
}else
return false;
}
public static int readNumber() {
boolean isValid = false;
int number;
do {
number = In.readInt() - 1;
if (!In.done()) {
Out.println("Input must be a valid number");
In.readLine();
} else if (number < 0 || number > 2) {
Out.println("The number is not in the specified range: 1-3");
} else {
isValid = true;
}
} while (!isValid);
return number;
}
public static boolean isTaken(int row, int col) {
return board[row][col] != '_';
}
}
EDIT: Need to change the do while loop,the part where the while loop should end while(isTaken(row,cel)) without the negation.Works now.
Thanks Norm, your the man!