I've got it now, here is the code should work.Thanks Norm,once again.This is my pre-last (I dont know if that word exists but I think you get it) assignment in my
programming class and if I get a positive Note, I will pass so wish me luck!
Here is the code;
public class TicTacToe {
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() {
int row,col;
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.print("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(!gameOver(row,col) && isBoardFull()) {
Out.println("Draw!");
playing = false;
}
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] != '_';
}
public static boolean isBoardFull() {
boolean isFull = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
isFull = false;
}
}
}
return isFull;
}
}