Why is the line printed twice? - java

I created a simple Tic Tac Toe game. Everything runs perfect except that at the end of the game, when the program decides the outcome it prints the last line twice. For example if player 1 wins it prints:
Player 1 has won
Player 1 has won
I've tried to write input.nextLine(); after the user enters the integer but with no luck.
Thanks in advance.
Here is my code:
public static void main(String[] args) {
//The board
char board[][] = new char [3][3];
//Players' characters
char player1 = 'X';
char player2 = 'O';
char turn = 0;
int rowNumber;
int columnNumber;
int count = 0;
//Welcome mesage
System.out.println("This is a tic tac toe game! \n\n");
System.out.println("Player1 - X \nPlayer 2 - O \n\n");
Scanner input = new Scanner(System.in);
//We display the board
board(board);
while (checkWin(board, player1) && checkWin(board, player2)
&& fullBoard(board)) {
count = count % 2;
if (count == 0) {
System.out.println("Player 1 turn! \n");
turn = player1;
count++;
} else if (count == 1) {
System.out.println("Player 2 turn!");
turn = player2;
count++;
}
while (true) {
System.out.println("Enter a row(1-3):");
rowNumber = input.nextInt();
System.out.println("Enter a column(1-3):");
columnNumber = input.nextInt();
if (board[rowNumber - 1][columnNumber - 1] != 'X'
&& board[rowNumber - 1][columnNumber - 1] != 'O') {
board[rowNumber - 1][columnNumber - 1] = turn;
break;
} else {
System.out.println("Place already taken. Enter again!");
}
}
board(board);
checkWin(board, player1);
checkWin(board, player2);
fullBoard(board);
}
System.out.println("Just checking;");
}
public static void board(char board[][]) {
System.out.println(board[0][0] + " | " + board[0][1] + " | "
+ board[0][2]);
System.out.println(board[1][0] + " | " + board[1][1] + " | "
+ board[1][2]);
System.out.println(board[2][0] + " | " + board[2][1] + " | "
+ board[2][2]);
}
public static boolean checkWin(char board[][], char player) {
if (board[0][0] == player && board[0][1] == player && board[0][2] == player ||
board[1][0] == player && board[1][1] == player && board[1][2] == player ||
board[2][0] == player && board[2][1] == player && board[2][2] == player ||
board[0][0] == player && board[1][0] == player && board[2][0] == player ||
board[0][1] == player && board[1][1] == player && board[2][1] == player ||
board[0][2] == player && board[1][2] == player && board[2][2] == player ||
board[0][0] == player && board[1][1] == player && board[2][2] == player ||
board[2][0] == player && board[1][1] == player && board[0][2] == player){
if(player == 'X'){
System.out.println("Player 1 has won!");
}
else if(player == 'O'){
System.out.println("Player 2 has won!");
}
return false;
}else {
return true;
}
}
public static boolean fullBoard(char board[][]) {
if ((board[0][0] == 'X' || board[0][0] == 'O')
&& (board[0][1] == 'X' || board[0][1] == 'O')
&& (board[0][2] == 'X' || board[0][2] == 'O')
&& (board[1][0] == 'X' || board[1][0] == 'O')
&& (board[1][1] == 'X' || board[1][1] == 'O')
&& (board[1][2] == 'X' || board[1][2] == 'O')
&& (board[2][0] == 'X' || board[2][0] == 'O')
&& (board[2][1] == 'X' || board[2][1] == 'O')
&& (board[2][2] == 'X' || board[2][2] == 'O')){
System.out.println("It's a tie!");
return false;
}else {
return true;
}
}
}

Because you are calling method twice, once in loop condition and second inside loop.
while (checkWin(board, player1) && checkWin(board, player2)
&& fullBoard(board)) {
....
checkWin(board, player1);
checkWin(board, player2);
}
You don't need to call it inside loop, in condition it is sufficient.
Change it to following...
while (checkWin(board, player1) && checkWin(board, player2)
&& fullBoard(board)) {
....
// Remove method call from here.
}

This is due to your while loop here :
while (checkWin(board, player1) && checkWin(board, player2)
&& fullBoard(board)){
// stuff
// and then again...
checkWin(board, player1);
checkWin(board, player2);
fullBoard(board);
}

Related

Restarting a while loop from the beginning / java

I have a game of tic tac toe that I need to play all the way through and then ask the user if they would like to play again.
I'm not sure how I would go about clearing the array and starting from the beginning of the loop.
I have a method at the very bottom of the code that I was thinking would possibly work but haven't had much luck with it.
Any help would be amazing thanks!
public class TicTacToe {
public static char[][] board = new char[3][3];
static Scanner scan = new Scanner(System.in);
public static String keepPlaying;
public static char yesOrNo;
public static void main(String[] args) {
User human1 = new User();
User human2 = new User();
human1.getUser1Name();
human2.getUser2Name();
System.out.println("\nPlayer 1: " + human1.human1Name() + ": X's");
System.out.println("Player 2: " + human2.human2Name() + ": O's\n");
initializeBoard();
displayBoard();
boolean playing = true;
while (playing) {
System.out.println("\n" + human1.human1Name() + " it's your turn.");
human1.getChoice();
human1.convert();
if (human1.returnRow() == 0 && human1.returnCol() == 0 && board[0][0] == ' ') {
board[0][0] = 'X';
displayBoard();
} else if (human1.returnRow() == 0 && human1.returnCol() == 1 && board[1][0] == ' ') {
board[1][0] = 'X';
displayBoard();
} else if (human1.returnRow() == 0 && human1.returnCol() == 2 && board[2][0] == ' ') {
board[2][0] = 'X';
displayBoard();
} else if (human1.returnRow() == 1 && human1.returnCol() == 0 && board[0][1] == ' ') {
board[0][1] = 'X';
displayBoard();
} else if (human1.returnRow() == 1 && human1.returnCol() == 1 && board[1][1] == ' ') {
board[1][1] = 'X';
displayBoard();
} else if (human1.returnRow() == 1 && human1.returnCol() == 2 && board[2][1] == ' ') {
board[2][1] = 'X';
displayBoard();
} else if (human1.returnRow() == 2 && human1.returnCol() == 0 && board[0][2] == ' ') {
board[0][2] = 'X';
displayBoard();
} else if (human1.returnRow() == 2 && human1.returnCol() == 1 && board[1][2] == ' ') {
board[1][2] = 'X';
displayBoard();
} else if (human1.returnRow() == 2 && human1.returnCol() == 2 && board[2][2] == ' ') {
board[2][2] = 'X';
displayBoard();
}
checkForWinner();
if (checkForWinner() == true) {
System.out.println("\n" + human1.human1Name() + " has won the game!!!");
break;
}
if (board[0][0] != ' ' && board[0][1] != ' ' && board[0][2] != ' ' && board[1][0] != ' '
&& board[1][1] != ' ' && board[1][2] != ' ' && board[2][0] != ' ' && board[2][1] != ' '
&& board[2][2] != ' ') {
System.out.println("It's a draw!!!");
break;
}
System.out.println("\n" + human2.human2Name() + " it's your turn.");
human2.getChoice();
human2.convert();
if (human2.returnRow() == 0 && human2.returnCol() == 0/* && board[0][0] == ' ' */) {
if (board[0][0] != ' ') {
System.out.println("\n" + human2.human2Name() + " that spot is already taken.");
human2.getChoice();
human2.convert();
continue;
}
board[0][0] = 'O';
displayBoard();
} else if (human2.returnRow() == 0 && human2.returnCol() == 1 && board[1][0] == ' ') {
board[1][0] = 'O';
displayBoard();
} else if (human2.returnRow() == 0 && human2.returnCol() == 2 && board[2][0] == ' ') {
board[2][0] = 'O';
displayBoard();
} else if (human2.returnRow() == 1 && human2.returnCol() == 0 && board[0][1] == ' ') {
board[0][1] = 'O';
displayBoard();
} else if (human2.returnRow() == 1 && human2.returnCol() == 1 && board[1][1] == ' ') {
board[1][1] = 'O';
displayBoard();
} else if (human2.returnRow() == 1 && human2.returnCol() == 2 && board[2][1] == ' ') {
board[2][1] = 'O';
displayBoard();
} else if (human2.returnRow() == 2 && human2.returnCol() == 0 && board[0][2] == ' ') {
board[0][2] = 'O';
displayBoard();
} else if (human2.returnRow() == 2 && human2.returnCol() == 1 && board[1][2] == ' ') {
board[1][2] = 'O';
displayBoard();
} else if (human2.returnRow() == 2 && human2.returnCol() == 2 && board[2][2] == ' ') {
board[2][2] = 'O';
displayBoard();
}
checkForWinner();
if (checkForWinner() == true) {
System.out.println("\n" + human2.human2Name() + " has won the game!!!");
break;
}
if (board[0][0] != ' ' && board[0][1] != ' ' && board[0][2] != ' ' && board[1][0] != ' '
&& board[1][1] != ' ' && board[1][2] != ' ' && board[2][0] != ' ' && board[2][1] != ' '
&& board[2][2] != ' ') {
System.out.println("It's a draw!!!");
break;
}
}
}
public TicTacToe() {
board = new char[3][3];
}
public static void initializeBoard() {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
board[row][col] = ' ';
}
}
}
public static void displayBoard() {
System.out.println(" A B C");
System.out.println(" -------------");
for (int row = 0; row < 3; row++) {
System.out.print((row + 1) + " | ");
for (int col = 0; col < 3; col++) {
System.out.print(board[row][col] + " | ");
}
System.out.println();
System.out.println(" -------------");
}
}
public static boolean checkForWinner() {
if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][1] != ' ') {
return true;
}
if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][1] != ' ') {
return true;
}
if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][1] != ' ') {
return true;
}
if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[1][0] != ' ') {
return true;
}
if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[1][1] != ' ') {
return true;
}
if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[1][2] != ' ') {
return true;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ') {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ') {
return true;
}
return false;
}
public static boolean playAgain() {
System.out.println("\nWould you like to play again?");
keepPlaying = scan.nextLine();
yesOrNo = keepPlaying.toUpperCase().charAt(0);
if (yesOrNo == 'N') {
return false;
} else if (yesOrNo == 'Y') {
return true;
}
return false;
}
}

Why does it not work when I input numOfTimes the code will stop running?(Name Generator)

I am a beginner in Java, and I have a question on why my code won't work. So basically when I set numOfTimes > 1 my program stops. Can anyone tell me why and how do I fix it? Thanks I will really appreciate if anyone helps me!
package CodingSets;
import java.util.*;
import java.util.*;
public class nameGenerator {
public static void rules() {
System.out.println("The rules arrr simple, give me the first
initial of your name, first intital of your middle name, and your last
initial");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char firstInitial;
char middleInitial;
char lastInitial;
int numOfTimes = 0;
System.out.print("How many times do you want to to enter your or your friends initials?\t");
numOfTimes = scan.nextInt();
int j = 1;
while (j == numOfTimes) {
String name = "";
System.out.print("Enter your first initial : ");
firstInitial = scan.next().charAt(0);
scan = new Scanner(System.in);
System.out.print("Enter your middle initial : ");
middleInitial = scan.next().charAt(0);
scan = new Scanner(System.in);
System.out.print("Enter your last initial : ");
lastInitial = scan.next().charAt(0);
if(firstInitial == 'a' || firstInitial == 'A') {
name += "Captain";
} else if (firstInitial == 'b' || firstInitial == 'B') {
name += "Dirty";
} else if (firstInitial == 'c' || firstInitial == 'C') {
name += "Squidlips";
} else if (firstInitial == 'd' || firstInitial == 'D') {
name += "Bowman";
} else if (firstInitial == 'e' || firstInitial == 'E') {
name += "Buccaneer";
} else if (firstInitial == 'f' || firstInitial == 'F') {
name += "Two Toes";
} else if (firstInitial == 'g' || firstInitial == 'G') {
name += "Sharkbait";
} else if (firstInitial == 'h' || firstInitial == 'H') {
name += "Old";
} else if (firstInitial == 'i' || firstInitial == 'I') {
name += "Peg Leg";
} else if (firstInitial == 'j' || firstInitial == 'J') {
name += "Fluffbucket";
} else if (firstInitial == 'k' || firstInitial == 'K') {
name += "Scallywag";
} else if (firstInitial == 'l' || firstInitial == 'L') {
name += "Bucko";
} else if (firstInitial == 'm' || firstInitial == 'M') {
name += "Dead Man";
} else if (firstInitial == 'n' || firstInitial == 'N') {
name += "Matey";
} else if (firstInitial == 'o' || firstInitial == 'O') {
name += "Jolly";
} else if (firstInitial == 'p' || firstInitial == 'P') {
name += "Stinky";
} else if (firstInitial == 'q' || firstInitial == 'Q') {
name += "Bloody";
} else if (firstInitial == 'r' || firstInitial == 'R') {
name += "Miss";
} else if (firstInitial == 's' || firstInitial == 'S') {
name += "Mad";
} else if (firstInitial == 't' || firstInitial == 'T') {
name += "Red";
} else if (firstInitial == 'u' || firstInitial == 'U') {
name += "Lady";
} else if (firstInitial == 'v' || firstInitial == 'V') {
name += "Bretheren";
} else if (firstInitial == 'w' || firstInitial == 'W') {
name += "Rapscallion";
} else if (firstInitial == 'x' || firstInitial == 'X') {
name += "Landlubber";
} else if (firstInitial == 'y' || firstInitial == 'Y') {
name += "Wrench";
} else if (firstInitial == 'z' || firstInitial == 'Z') {
name += "Freebooter";
} else {
System.out.println("Bruh learn ur alphebet");
}
if(middleInitial == 'a' || middleInitial == 'A') {
name += " Creeper";
} else if (middleInitial == 'b' || middleInitial == 'B') {
name += " Jim";
} else if (middleInitial == 'c' || middleInitial == 'C') {
name += " Storm";
} else if (middleInitial == 'd' || middleInitial == 'D') {
name += " John";
} else if (middleInitial == 'e' || middleInitial == 'E') {
name += " George";
} else if (middleInitial == 'f' || middleInitial == 'F') {
name += " O'";
} else if (middleInitial == 'g' || middleInitial == 'G') {
name += " Rat";
} else if (middleInitial == 'h' || middleInitial == 'H') {
name += " Jack";
} else if (middleInitial == 'i' || middleInitial == 'I') {
name += " Legs";
} else if (middleInitial == 'j' || middleInitial == 'J') {
name += " Head";
} else if (middleInitial == 'k' || middleInitial == 'K') {
name += " Cackle";
} else if (middleInitial == 'l' || middleInitial == 'L') {
name += " Patch";
} else if (middleInitial == 'm' || middleInitial == 'M') {
name += " Bones";
} else if (middleInitial == 'n' || middleInitial == 'N') {
name += " Plank";
} else if (middleInitial == 'o' || middleInitial == 'O') {
name += " Greedy";
} else if (middleInitial == 'p' || middleInitial == 'P') {
name += " Sea";
} else if (middleInitial == 'q' || middleInitial == 'Q') {
name += " Mama";
} else if (middleInitial == 'r' || middleInitial == 'R') {
name += " Spike";
} else if (middleInitial == 's' || middleInitial == 'S') {
name += " Squiffy";
} else if (middleInitial == 't' || middleInitial == 'T') {
name += " Gold";
} else if (middleInitial == 'u' || middleInitial == 'U') {
name += " Yellow";
} else if (middleInitial == 'v' || middleInitial == 'V') {
name += " Felony";
} else if (middleInitial == 'w' || middleInitial == 'W') {
name += " Eddie";
} else if (middleInitial == 'x' || middleInitial == 'X') {
name += " Bay";
} else if (middleInitial == 'y' || middleInitial == 'Y') {
name += " Thomas";
} else if (middleInitial == 'z' || middleInitial == 'Z') {
name += " Spot";
} else {
System.out.println("Bruh learn ur alphebet");
}
if(lastInitial == 'a' || lastInitial == 'A') {
name += " From the West";
} else if (lastInitial == 'b' || lastInitial == 'B') {
name += " Byrd";
} else if (lastInitial == 'c' || lastInitial == 'C') {
name += " Jackson";
} else if (lastInitial == 'd' || lastInitial == 'D') {
name += " Sparrow";
} else if (lastInitial == 'e' || lastInitial == 'E') {
name += " Of the Coast";
} else if (lastInitial == 'f' || lastInitial == 'F') {
name += " Jones";
} else if (lastInitial == 'g' || lastInitial == 'G') {
name += " Ned Head";
} else if (lastInitial == 'h' || lastInitial == 'H') {
name += " Bart";
} else if (lastInitial == 'i' || lastInitial == 'I') {
name += " O'Fish";
} else if (lastInitial == 'j' || lastInitial == 'J') {
name += " Kidd";
} else if (lastInitial == 'k' || lastInitial == 'K') {
name += " O'Malley";
} else if (lastInitial == 'l' || lastInitial == 'L') {
name += " Barnacle";
} else if (lastInitial == 'm' || lastInitial == 'M') {
name += " HolyStone";
} else if (lastInitial == 'n' || lastInitial == 'N') {
name += " Hornswaggle";
} else if (lastInitial == 'o' || lastInitial == 'O') {
name += " McStinky";
} else if (lastInitial == 'p' || lastInitial == 'P') {
name += " Swashbuckler";
} else if (lastInitial == 'q' || lastInitial == 'Q') {
name += " Sea Wolf";
} else if (lastInitial == 'r' || lastInitial == 'R') {
name += " Beard";
} else if (lastInitial == 's' || lastInitial == 'S') {
name += " Chumbucket";
} else if (middleInitial == 't' || lastInitial == 'T') {
name += " Rivers";
} else if (middleInitial == 'u' || lastInitial == 'U') {
name += " Morgan";
} else if (lastInitial == 'v' || lastInitial == 'V') {
name += " Tuna Breath";
} else if (lastInitial == 'w' || lastInitial == 'W') {
name += " Three Gates";
} else if (lastInitial == 'x' || lastInitial == 'X') {
name += " Bailey";
} else if (lastInitial == 'y' || lastInitial == 'Y') {
name += " Of Atlantis";
} else if (lastInitial == 'z' || lastInitial == 'Z') {
name += " Of Dark Water";
} else {
System.out.println("Bruh learn ur alphebet");
}
System.out.println("Your pirate name is " + name);
j++;
}
}
}
The First Image Is The Code Where numOfTimes = 1, The Second Image Is The Not Working Code Where numOfTimes > 1
It doesn't work because the condition j == numOfTimes is false, therefore nothing in the loop actually is executed. Change it to j <= numOfTimes.

Java program terminated before running

import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
board b = new board();
while (!b.detectWin('x') && !b.detectWin('o') && !b.detectTie()) {
b.printBoard();
System.out.println("Player 1, where do you want to put an x?");
int xAnswer = input.nextInt();
b.setSpot('x', xAnswer);
b.printBoard();
System.out.println("Player 2, where do you want to put an o?");
int oAnswer = input.nextInt();
b.setSpot('o', oAnswer);
b.printBoard();
if(b.detectWin('x')) {
System.out.println("Player 1 won!");
}else if (b.detectWin('o')) {
System.out.println("Player 2 won!");
}else {
System.out.println("There was a tie.");
}
}
}
}
It's a tic tac toe program, here's the board:
public class board {
private char[] board;
public board() {
board = new char[]
{'0', '1', '2',
'3', '4', '5',
'6', '7', '8'};
}
public void setSpot(char player, int position) {
if (board[position] == position+48) {
board[position] = player;
}else {
System.out.println("Incorrect move, turn skipped");
}
}
public boolean detectWin(char player){
if((board[0] == player && board[1] == player && board[2] == player)
|| (board[3] == player && board[4] == player && board[5] == player) ||
(board[6] == player && board[7] == player && board[8] == player) ||
(board[0] == player && board[3] == player && board[6] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[0] == player && board[4] == player && board[8] == player) ||
(board[2] == player && board[4] == player && board[6] == player))
return true;
else
return false;
}
public boolean detectTie() {
for (int i = 0; i > board.length; i++) {
if (board[i] == i+48)
return false;
}
return true;
}
public void printBoard() {
System.out.println(board[0] + " | " +board[1] +" | " +board[2]);
System.out.println("---------");
System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
System.out.println("--------");
System.out.println(board[6] + " | " + board [7] + " | " + board[8]);
}
}
It keeps getting terminated, and I can't find out why. No error messages.
(placeholder for post is mostly code error placeholder for post is mostly code error placeholder for post is mostly code error placeholder for post is mostly code error placeholder for post is mostly code error
simple typo in your code, change detectTie as follows:
public boolean detectTie() {
for (int i = 0; i < board.length; i++) {
if (board[i] == i+48)
return false;
}
return true;
}
and you should be good. you were using int i = 0; i > board.length; i++, so i was starting with 0, and that was not greater than the board arrays length so it never executed the loop and just returned true, this in turn caused !b.detectTie() to return false, meaning the main while loop was never executed.

Passing a boolean result into another methods if statement. (tic-tac-toe game)

public boolean isWinner(char player)
{
if (board[0] == player && board[1] == player && board[2] == player ||
board[3] == player && board[4] == player && board[5] == player ||
board[6] == player && board[7] == player && board[8] == player ||
board[0] == player && board[3] == player && board[6] == player ||
board[1] == player && board[4] == player && board[7] == player ||
board[2] == player && board[5] == player && board[8] == player )
return true;
return false;
}
/* check to see if the player x is the winner or
the player y is the winner or the cat is the winner
or the game is not over yet and then display the result
you need to write conditional statments*/
public void displayResults()
{
if (isWinner = true)
System.out.print("CONGRATUTIONS " + player + " YOU WON!");
}
Hey I was wondering if anyone could help me on how to pass the the "isWinner" result into "displayResults" if statement. This is for a tic-tac-toe game that we got assigned if this is one of the parts I need help on.
Running under the assumption that player is an accessible char object...
public void displayResults()
{
if (isWinner(player))
System.out.print("CONGRATULATIONS " + player + " YOU WON!");
// ^^^^
// Fix your typo too
}
First of all, isWinner should return true or false, not 1 or 0.
Second of all,
if (isWinner = true)
should be
if (isWinner(player))
assuming player is a char that represents a player, since that's what isWinner() requires.

Java - Tic Tac Toe - Why won't my "switch player" method work?

Why does my switchPlayer() method only work once? The method should work independently just fine, and when I put it inside my playGame() method after placeMark(), it works continuously, but that messes up my currentPlayer variable, which messes up other methods. I do not want to make a player object, so I assume I am just missing something simple, like where to place the switchPlayer() method.
My result goes like this:
currentplayer 1, place your mark.
[places mark, all good]
currentplayer 2, place your mark.
[places mark, all good]
currentplayer 2, place your mark. // problem line.. doesn't switch
[places mark, all good]
Relevant code for sub class:
public void playGame(){
assignNames();
assignMarks();
explainGame();
while(checkWin() == false && fullBoard() == false){
getNum();
placeMark();
printBoard();
}
gameResult();
}
public void placeMark(){
if(validNumber() == true){
if(num == 1){
board[0][0] = currentMark;
switchPlayer();
}
if(num == 2){
board[0][1] = currentMark;
switchPlayer();
}
if(num == 3){
board[0][2] = currentMark;
switchPlayer();
}
if(num == 4){
board[1][0] = currentMark;
switchPlayer();
}
if(num == 5){
board[1][1] = currentMark;
switchPlayer();
}
if(num == 6){
board[1][2] = currentMark;
switchPlayer();
}
if(num == 7){
board[2][0] = currentMark;
switchPlayer();
}
if(num == 8){
board[2][1] = currentMark;
switchPlayer();
}
if(num == 9){
board[2][2] = currentMark;
switchPlayer();
}
}
}
public void switchPlayer(){
if(currentMark == 'X')
currentMark = 'O';
else{
currentMark = 'X';
}
if(currentMark == 'O' && playerMark1 == 'O'){
currentPlayer = playerName1;
}
else{
currentPlayer = playerName2;
}
}
Relevant code for main class:
TicTacToe game = new TicTacToe();
game.playGame();
It seems as though I should just post the whole code... so here it is.
public class TicTacToe {
private static char[][] board;
Scanner input = new Scanner(System.in);
int num;
String entry;
String playerName1;
char playerMark1;
String playerName2;
char playerMark2;
char currentMark;
String currentPlayer;
public void playGame(){
assignNames();
assignMarks();
explainGame();
while(checkWin() == false && fullBoard() == false){
getNum();
placeMark();
printBoard();
}
gameResult();
}
public TicTacToe(){
board = new char[3][3];
clearBoard();
} // end TicTacToe()
public void clearBoard(){
for(int a = 0; a < 3; a++){
for(int b = 0; b < 3; b++){
board[a][b] = ' ';
}
}
}// end clearBoard()
public void printBoard(){
System.out.println("-------------");
for (int a = 0; a < 3; a++) {
System.out.print("| ");
for (int b = 0; b < 3; b++) {
System.out.print(board[a][b] + " | ");
}
System.out.println();
System.out.println("-------------");
}
}
public boolean fullBoard() {
boolean full = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
full = false;
}
}
}
return full;
}
public void explainGame(){
System.out.println("-------------");
System.out.println("| 1 | 2 | 3 |");
System.out.println("-------------");
System.out.println("| 4 | 5 | 6 |");
System.out.println("-------------");
System.out.println("| 7 | 8 | 9 |");
System.out.println("-------------");
System.out.println("The above board shows which numbers you must enter to place your mark in their respective locations.\n");
System.out.println("Randomly assigning player marks. . .");
System.out.println(playerName1+" will be Player "+playerMark1+", and "+playerName2+" will be Player "+playerMark2 + ".");
System.out.println("Player X will go first. Press any key to begin playing.");
entry = input.nextLine();
}
public void assignNames(){
System.out.println("Enter a name for Player 1.");
entry = input.nextLine();
playerName1 = entry;
System.out.println("Enter a name for Player 2.");
entry = input.nextLine();
playerName2 = entry;
}
public void assignMarks(){
Random rand = new Random();
int i = rand.nextInt(2);
if( i == 0 ){
playerMark1 = 'X';
playerMark2 = 'O';
}
else{
playerMark1 = 'O';
playerMark2 = 'X';
}
currentMark = 'X';
if(playerMark1 == 'X')
currentPlayer = playerName1;
else
currentPlayer = playerName2;
}
public void switchPlayer(){
if(currentMark == 'X')
currentMark = 'O';
else{
currentMark = 'X';
}
if(currentMark == 'O' && playerMark1 == 'O'){
currentPlayer = playerName1;
}
else{
currentPlayer = playerName2;
}
}
public int getNum(){
System.out.println(currentPlayer + ", place your mark (1-9).");
num = input.nextInt();
return num;
}
public boolean validSpot(int num){
boolean goodSpot = false;
if(num == 1 && board[0][0] == ' ')
goodSpot = true;
if(num == 2 && board[0][1] == ' ')
goodSpot = true;
if(num == 3 && board[0][2] == ' ')
goodSpot = true;
if(num == 4 && board[1][0] == ' ')
goodSpot = true;
if(num == 5 && board[1][1] == ' ')
goodSpot = true;
if(num == 6 && board[1][2] == ' ')
goodSpot = true;
if(num == 7 && board[2][0] == ' ')
goodSpot = true;
if(num == 8 && board[2][1] == ' ')
goodSpot = true;
if(num == 9 && board[2][2] == ' ')
goodSpot = true;
if(goodSpot == false){
System.out.println("Input error. Make sure the spot is not taken.");
}
return goodSpot;
}
public boolean validRange(int num){
boolean goodRange = false;
if(num >= 1 && num <= 9 ){
goodRange = true;
}
if(goodRange == false){
System.out.println("Input error. Make sure the number is between 1-9.");
}
return goodRange;
}
public boolean validNumber(){
return ((validRange(num) && validSpot(num)));
}
public void placeMark(){
if(validNumber() == true){
if(num == 1){
board[0][0] = currentMark;
switchPlayer();
}
if(num == 2){
board[0][1] = currentMark;
switchPlayer();
}
if(num == 3){
board[0][2] = currentMark;
switchPlayer();
}
if(num == 4){
board[1][0] = currentMark;
switchPlayer();
}
if(num == 5){
board[1][1] = currentMark;
switchPlayer();
}
if(num == 6){
board[1][2] = currentMark;
switchPlayer();
}
if(num == 7){
board[2][0] = currentMark;
switchPlayer();
}
if(num == 8){
board[2][1] = currentMark;
switchPlayer();
}
if(num == 9){
board[2][2] = currentMark;
switchPlayer();
}
}
}
public boolean checkSpot(char c1, char c2, char c3) {
return ((c1 != ' ') && (c1 == c2) && (c2 == c3));
}
public boolean checkWin() {
return (checkWinRows() || checkWinColumns() || checkWinDiagonals());
}
public boolean checkWinRows() {
for (int i = 0; i < 3; i++) {
if (checkSpot(board[i][0], board[i][1], board[i][2]) == true) {
return true;
}
}
return false;
}
public boolean checkWinColumns() {
for (int i = 0; i < 3; i++) {
if (checkSpot(board[0][i], board[1][i], board[2][i]) == true) {
return true;
}
}
return false;
}
public boolean checkWinDiagonals() {
return ((checkSpot(board[0][0], board[1][1], board[2][2]) == true) || (checkSpot(board[0][2], board[1][1], board[2][0]) == true));
}
public void gameResult(){
switchPlayer();
if(checkWin()){
System.out.println("\nGAME OVER -- " +currentPlayer+ " WINS! WOO HOO!");
}
else if(fullBoard()){
System.out.println("\nGAME OVER -- DRAW!");
}
}
} // end TicTacToe
Change
if(currentMark == 'O' && playerMark1 == 'O')
to
if(currentPlayer==playerName2)
Your code doesn't always work because it only changes to player one when both current mark = 0 and player1 mark = 0. This is, it only works when player one was assigned "O" in the beginning of the game.
Hope it helps.
The switch player code does nothing if both the current and player1 mark is X. Try:
if (currentMark == playerMark1){
currentPlayer = playerName1;
} else {
currentPlayer = playerName2;
}

Categories

Resources