TicTacToe Doesn't Display All Letters [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I created a TicTacToe game and I can't figure out why it won't display the last letter when someone wins. Like if you get 3 in a row it will display only the 2 letters but won't display the winning letter if that makes any sense.
TicTacToe Class Code:
import java.util.Scanner;
import javax.swing.JFrame;
public class TicTacToe {
public static void main(String [] args) {
Board board = new Board();
Rules winner = new Rules();
Scanner input = new Scanner(System.in);
int slot;
int swap = 1;
System.out.print("Player 1 Name: ");
String player1 = input.next();
System.out.print('\f');
System.out.print("Player 2 Name: ");
String player2 = input.next();
System.out.print('\f');
System.out.print(player1 + ", Choose X or O: ");
String letter = input.next();
System.out.print('\f');
String player1Letter;
String player2Letter;
if (letter.equalsIgnoreCase("x")) {
player1Letter = "X";
player2Letter = "O";
} else {
player1Letter = "O";
player2Letter = "X";
}
System.out.println("This is how each number is set on the board");
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("Each number represents the slot number. For example if you wanted to");
System.out.println("Place an 'X' or an 'O' in the very middle, you would choose slot 5");
System.out.println();
while (true) {
System.out.print("Type 'begin' to begin: ");
String begin = input.next();
if (begin.equalsIgnoreCase("begin")) {
break;
} else if (!begin.equalsIgnoreCase("begin")) {
System.out.println();
System.out.println("Incorrect Syntax");
}
}
while (true) {
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}
if (winner.isWinner(board) == true) {
JFrame frame = new JFrame();
frame.setSize(150, 250);
frame.setTitle("A Simley Face");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FaceComponent component = new FaceComponent();
frame.add(component);
frame.setVisible(true);
}
}
}
Board Class Code:
public class Board
{
private String position;
String topLeft= "1";
String topMiddle= "2";
String topRight= "3";
String middleLeft= "4";
String middleMiddle= "5";
String middleRight= "6";
String bottomLeft= "7";
String bottomMiddle= "8";
String bottomRight= "9";
public String getPosition(int pos)
{
if (pos == 1)
{
return topLeft;//varible of position 1
}
else if (pos == 2)
{
return topMiddle;//varible of position 2
}
else if (pos == 3)
{
return topRight;//varible of position 3
}
else if (pos == 4)
{
return middleLeft;//varible of position 4
}
else if (pos == 5)
{
return middleMiddle;//varible of position 5
}
else if (pos == 6)
{
return middleRight;//varible of position 6
}
else if (pos == 7)
{
return bottomLeft;//varible of position 7
}
else if (pos == 8)
{
return bottomMiddle;//varible of position 8
}
else if (pos == 9)
{
return bottomRight;//varible of position 9
}
return position;
}
public String setPosition(int pos, String value)
{
if (pos == 1)
{
topLeft = value;
}
else if (pos == 2)
{
topMiddle = value;
}
else if (pos == 3)
{
topRight = value;
}
else if (pos == 4)
{
middleLeft = value;
}
else if (pos == 5)
{
middleMiddle = value;
}
else if (pos == 6)
{
middleRight = value;
}
else if (pos == 7)
{
bottomLeft = value;
}
else if (pos == 8)
{
bottomMiddle = value;
}
else if (pos == 9)
{
bottomRight = value;
}
return position;
}
}
Rules Class Code:
public class Rules
{
private String winner;
private String threeInARow;
public boolean isWinner(Board threeInARow)
{
String pos1 = threeInARow.getPosition(1);
String pos2 = threeInARow.getPosition(2);
String pos3 = threeInARow.getPosition(3);
String pos4 = threeInARow.getPosition(4);
String pos5 = threeInARow.getPosition(5);
String pos6 = threeInARow.getPosition(6);
String pos7 = threeInARow.getPosition(7);
String pos8 = threeInARow.getPosition(8);
String pos9 = threeInARow.getPosition(9);
if (pos1.equals(pos2) && pos2.equals(pos3))
{
return true;
}
else if (pos4.equals(pos5) && pos5.equals(pos6))
{
return true;
}
else if (pos7.equals(pos8) && pos8.equals(pos9))
{
return true;
}
else if (pos1.equals(pos4) && pos4.equals(pos7))
{
return true;
}
else if (pos2.equals(pos5) && pos5.equals(pos8))
{
return true;
}
else if (pos3.equals(pos6) && pos6.equals(pos9))
{
return true;
}
else if (pos1.equals(pos5) && pos5.equals(pos9))
{
return true;
}
else if (pos3.equals(pos5) && pos5.equals(pos7))
{
return true;
}
else
{
return false;
}
}
}
FaceComponent class Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class FaceComponent extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Draw the head
Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
g2.draw(head);
// Draw the eyes
g2.setColor(Color.BLACK);
Rectangle eye = new Rectangle(25, 70, 15, 15);
g2.fill(eye);
eye.translate(50, 0);
g2.fill(eye);
// Draw the mouth
Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
g2.setColor(Color.RED);
g2.draw(mouth);
// Draw the greeting
g2.setColor(Color.BLUE);
g2.drawString("YOU ARE A WINNER", 5, 175);
}
}

why it won't display the last letter when someone wins.
This is happening because in your main method, after you have received the user input, you are changing the location selected by user to to letter of the player. Then you are going on to check if the player is a winner or not. If the player is not a winner then you go on to draw the board and wait for the next player input. But if the player is a winner then you simply display the message and exit the loop without redrawing the board.
The solution is you could draw the board again inside the if condition of checking the winner then display the message and exit the loop.
I would suggest that you declare a method say draw board in your class TicTacToe as shown below:
private void drawBoard(Board board){
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
}
Now change your while loop for drawing the board and getting user input from:
while (true) {
System.out.print('\f');
System.out.println(" " + board.getPosition(1) + " | " + board.getPosition(2) + " | " + board.getPosition(3) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(4) + " | " + board.getPosition(5) + " | " + board.getPosition(6) + " ");
System.out.println("----------------");
System.out.println(" " + board.getPosition(7) + " | " + board.getPosition(8) + " | " + board.getPosition(9) + " ");
System.out.println();
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}
to :
while (true) {
drawBoard(board); //Replace with draw board
System.out.print("Choose A Slot: ");
slot = input.nextInt();
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) {
board.setPosition(slot, player1Letter);
swap++;
} else if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
board.setPosition(slot, player2Letter);
swap++;
}
if (winner.isWinner(board) == true) {
drawBoard(board); // Add the draw board.
if (swap == 1 || swap == 3 || swap == 5 || swap == 7 || swap == 9 || swap == 11) { //swap%2 == 1
System.out.println();
System.out.print(player2 + " Wins!");
break;
}
if (swap == 2 || swap == 4 || swap == 6 || swap == 8 || swap == 10 || swap == 12) {
System.out.println();
System.out.print(player1 + " Wins!");
break;
} else if (winner.isWinner(board) == false) {
System.out.println();
System.out.print("Tie Game");
break;
}
}
}

Related

making java tic tac toe vs computer [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Thats my tictactoe game and i have this problem i cant find out...When i compile my programm
Welcome To Tic Tac Toe Professor Falken!
***Use Numbers 1-9 To Select A Square***
_1_|_2_|_3_|
_4_|_5_|_6_|
_7_|_8_|_9_|
You Go First!
___|___|___|
___|___|___|
___|___|___|
Player X, enter move (1 - 9):
10
INVALID MOVE: Enter number 1 - 9 only:
5
___|___|___|
___|_X_|___|
___|___|___|
Player O, enter move (1 - 9):
___|___|___|
___|_X_|_O_|
___|___|___|
Player X, enter move (1 - 9):
4
___|___|___|
_X_|_X_|_O_|
___|___|___|
Player O, enter move (1 - 9):
And stops there, i dont know why can anyone help me?
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private Scanner in;
private boardPiece[][] board = {{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()}};
private char turn = 'X';
private boolean win = false;
private int count = 0;
private Random random = new Random();
private int randomNumber = random.nextInt(9);
public static void main(String [] args)
{
int replay;
TicTacToe game = new TicTacToe();
game.in = new Scanner(System.in);
System.out.println("Welcome To Tic Tac Toe Professor Falken!");
System.out.println("***Use Numbers 1-9 To Select A Square***");
System.out.println("_1_|_2_|_3_|");
System.out.println("_4_|_5_|_6_|");
System.out.println("_7_|_8_|_9_|");
System.out.println(" n You Go First!");
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
while(replay != 2){
game.init();
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
}
game.in.close();
System.out.println("How about a nice game of chess :p");
}
public void play()
{
printBoard();
while(!win)
move();
}
public void printBoard()
{
for(int x=0; x<3; x++){
for(int y=0; y<3; y++){
System.out.print(board[x][y].piece);
}
System.out.println();
}
}
public void move()
{
int move = 0;
String valid = "";
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if(turn == 'O') {
move = randomNumber; }
else {
move = in.nextInt();
}
valid = checkMove(move);
while(valid != "ok")
{
if(turn == 'X') {
System.out.println("INVALID MOVE: "+ valid);
move = in.nextInt();
}
else {
move = randomNumber;
}
valid = checkMove(move);
}
count++;
board[(move-1)/3][(move-1)%3].piece = "_"+turn+"_|";
board[(move-1)/3][(move-1)%3].player = turn;
board[(move-1)/3][(move-1)%3].used = true;
printBoard();
if(count >= 5)
checkWin(move);
if(turn == 'X')
turn = 'O';
else
turn = 'X';
}
public String checkMove(int move)
{
if(move < 1 || move > 9)
return "Enter number 1 - 9 only: ";
else
if(board[(move-1)/3][(move-1)%3].used)
return "That move has been used. Enter another move (1 - 9): ";
else
return "ok";
}
public void checkWin(int move)
{
for(int x = 0; x<3; x++){ //Horizontal
if((board[x][0].used && board[x][1].used && board[x][2].used) &&
(board[x][0].player == board[x][1].player && board[x][0].player == board[x][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
for(int y = 0; y<3; y++)
{
if((board[0][y].used && board[1][y].used && board[2][y].used) &&
(board[0][y].player == board[1][y].player && board[0][y].player == board[2][y].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
if((board[0][0].used && board[1][1].used && board[2][2].used) &&
(board[0][0].player == board[1][1].player && board[0][0].player == board[2][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if((board[2][0].used && board[1][1].used && board[0][2].used) &&
(board[2][0].player == board[1][1].player && board[2][0].player == board[0][2].player))
{
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if(count==9){
System.out.println("Draw! Nobody Wins (´???`)");
win = true;
return;
}
}
public void init()
{
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
board[x][y] = new boardPiece();
}
}
turn = 'X';
win = false;
count = 0;
}
class boardPiece{
public String piece;
public char player;
public boolean used;
boardPiece(){
piece = "___|";
used = false;
}
}
}
I made a some changes in move and checkMove
public void move() {
int move = 0;
Boolean valid = false;
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if (turn == 'O') {
move = randomNumber;
} else {
move = in.nextInt();
}
valid = checkMove(move);
while (!valid) {
if (turn == 'X') {
move = in.nextInt();
} else {
move = random.nextInt(9);
}
valid = checkMove(move);
}
count++;
board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_|";
board[(move - 1) / 3][(move - 1) % 3].player = turn;
board[(move - 1) / 3][(move - 1) % 3].used = true;
printBoard();
if (count >= 5) {
checkWin(move);
}
if (turn == 'X') {
turn = 'O';
}else {
turn = 'X';
}
}
public Boolean checkMove(int move) {
if (move < 1 || move > 9) {
System.out.println("INVALID MOVE: Enter number 1 - 9 only: ");
return false;
}else if (board[(move - 1) / 3][(move - 1) % 3].used) {
System.out.println("INVALID MOVE: That move has been used. Enter another move (1 - 9): ");
return false;
}else {
return true;
}
}

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.

Unknown issue finding symbol in Java code

First off, I'm pretty green when it comes to java. So, I'm making a rock paper scissors game with 2 classes and an object connecting the two. For some unknown reason, when I use the object, it cannot find the method im pointing to. The error is "cannot find symbol" and is in the first class where it is game.RockPaperScissors();
public class RPSRunner {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
char response;
//add in a do while loop after you get the basics up and running
out.print("type in your prompt [R,P,S] :: ");
String player = keyboard.nextLine();
RockPaperScissors game = new RockPaperScissors();
do {
game. **RockPaperScissor **(player);
} while (player == r || p || s);
}
}
and
public class RockPaperScissors {
String playChoice;
String compChoice;
Random random = new Random();
int rand = 0;
public RockPaperScissors() {
playChoice = " ";
compChoice = " ";
}
public RockPaperScissors(String player) {
setPlayers(player);
}
public void setPlayers(String player) {
playChoice = player;
rand = random.nextInt(3);
if (rand == 0) {
compChoice = "r";
}
if (rand == 1) {
compChoice = "p";
}
if (rand == 2) {
compChoice = "s";
}
System.out.println("player had " + playChoice);
System.out.println("computer had " + compChoice);
}
public String determineWinner() {
String winner = "";
if ((compChoice == "r") && (playChoice == "p")) ;
{
winner = "!Player wins << Paper covers Rock>>!";
}
if ((compChoice == "r") && (playChoice == "s")) ;
{
winner = "! Computer wins << Rock breaks Scissors >>!";
}
if ((compChoice == "p") && (playChoice == "r")) ;
{
winner = "! Computer wins << Paper covers Rock>>!";
}
if ((compChoice == "p") && (playChoice == "s")) ;
{
winner = "!Player wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "p")) ;
{
winner = "! Computer wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "r")) ;
{
winner = "!Player wins << Rock breaks Scissors >>!";
}
if (compChoice == playChoice) ;
{
winner = " !Tie << Both the computer and player have selected " + compChoice + " >>!";
}
return winner;
}
public String toString() {
String output = "";
return output;
}
}
Change
public RockPaperScissors(String player)
To
public void RockPaperScissors(String player)
The former is a constructor while the latter is a method. Also,there seems to be numerous other problems in your code(like the condition of the do...while loop,using == to compare Strings etc)

Have to write a Tic Tac Toe game for 2 players [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
import java.util.Scanner;
public class gameBoard
{
public static void main(String[] args)
{
String str1;
Scanner scan = new Scanner(System.in);
System.out.println("Player 1 please enter 1 or 2, 1 = O, 2 = X");
int a = scan.nextInt();
if(a == 1){
String str2 = "O";
str1 = str2;
}else{
String str2 = "X";
str1 = str2;
}
System.out.println("Player 1 please enter the ROW (1, 2 or 3) you want: ");
int b = scan.nextInt();
if (b == 1 || b == 2 || b == 3){
System.out.println("Player 1 please enter the COLUMN you want: ");
int c = scan.nextInt();
if( c == 1 || c == 2 || c == 3){
if ( b == 2 && c == 2){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | " + str1 + " | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (b == 1 && c == 1){
System.out.println(str1 + " | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (b == 2 && c == 1){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(str1 + " | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (b == 3 && c == 1){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(str1 + " | | ");
}
if (b == 1 && c == 2){
System.out.println(" | " +str1 + " | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if( b == 3 && c == 2){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | " + str1 + "| ");
}
if (b == 1 && c == 3){
System.out.println(" | |" + str1);
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (b == 2 && c == 3){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | " + str1);
System.out.println("-----------");
System.out.println(" | | ");
}
if ( b == 3 && c == 3){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | " + str1);
}
System.out.println("Player 2 please enter 1 or 2, 1 = O, 2 = X");
int e = scan.nextInt();
if(e == 1){
String str2 = "O";
str1 = str2;
}else{
String str2 = "X";
str1 = str2;
}
System.out.println("Player 2 please enter the ROW (1, 2 or 3) you want: ");
int f = scan.nextInt();
if (f == 1 || f == 2 || f == 3){
System.out.println("Player 2 please enter the COLUMN you want: ");
int g = scan.nextInt();
if( g == 1 || g == 2 || g == 3){
if ( f == 2 && g == 2){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | " + str1 + " | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (f == 1 && g == 1){
System.out.println(str1 + " | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (f == 2 && g == 1){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(str1 + " | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (f == 3 && g == 1){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(str1 + " | | ");
}
if (f == 1 && g == 2){
System.out.println(" | " +str1 + " | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if( f == 3 && g == 2){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | " + str1 + "| ");
}
if (f == 1 && g == 3){
System.out.println(" | |" + str1);
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
}
if (f == 2 && g == 3){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | " + str1);
System.out.println("-----------");
System.out.println(" | | ");
}
if ( f == 3 && g == 3){
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | ");
System.out.println("-----------");
System.out.println(" | | " + str1);
}
System.out.println("");
}
}
}
}
}
}
I'm writing this thing entirely with if statements right now and I feel like this is an inherently wrong approach to this task. I can get the first move of each player but I cannot figure out a way to "save" the state the board is in after the first player moves, its just prints a board with player 1's first move, then prints a board with player 2's first move, but they are not on the same board together. I feel a bit out of my league here...
You should be more inclined to use fields (for "saving") and methods (for re-using bits of code)
Try this example:
import java.util.Scanner;
public class GameBoard {
// Use a matrix to emulate a 3*3 grid.
private String[][] board = new String[3][3];
private String[][] players = { { "Player 1", "X" }, { "Player 2", "O" } };
private int currentPlayer = -1;
public boolean isBoardFull() {
for (String[] row : board) {
for (String col : row) {
if (col == null) {
return false;
}
}
}
return true;
}
public boolean gameIsWon() {
// I shall leave this to your imagination ;)
return false;
}
public void printBoard() {
for (String[] row : board) {
for (String col : row) {
System.out.print("|" + (col == null ? " " : col) + "|");
}
System.out.println("\n---------");
}
}
public void play() {
// Try-with-resource (Java 7+)
try (Scanner scanner = new Scanner(System.in)) {
while (!isBoardFull()) {
currentPlayer = (currentPlayer + 1) % 2;
boolean valid = false;
// Loop until a certain player makes a valid move
while (!valid) {
System.out.print(players[currentPlayer][0] + ", choose your row: \n> ");
int row = scanner.nextInt() - 1;
System.out.print(players[currentPlayer][0] + ", you have chosen row " + (row + 1) + ". Choose your column: \n> ");
int col = scanner.nextInt() - 1;
if (board[row][col] == null) {
board[row][col] = players[currentPlayer][1];
printBoard();
if (gameIsWon()) {
System.out.println(players[currentPlayer][0] + " wins!");
return;
}
valid = true; // This will allow players to switch turns
} else {
System.out.println("This slot is taken, try again!");
}
}
}
System.out.println("Draw!");
}
}
public static void main(String[] args) {
new GameBoard().play();
}
}
I made a new class from yours, this one will save elements from user input, just complete it:
import java.util.Scanner;
public class gameBoard {
public static void main(String[] args) {
int n = 1, j, i, b;
char str1 = 'o';
Scanner scan = new Scanner(System.in);
char[][] g = new char[3][3];
for(i = 0; i < 3; i ++){
for(j = 0; j < 3; j ++){
if(j == 2){
System.out.print(n);
}
else{
System.out.print(n + " | ");
}
g[i][j] = ' ';
n++;
}
System.out.println("");
}
n = 1;
System.out.println("Player 1 please enter the square you want (1-9): ");
b = scan.nextInt();
while(b > 9 || b < 1){
System.out.println("Player 1 please enter the square you want (1-9): ");
b = scan.nextInt();
}
switch(b){
case 1:
if(g[0][0] == ' '){
g[0][0] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 2:
if(g[0][1] == ' '){
g[0][1] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 3:
if(g[0][2] == ' '){
g[0][2] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 4:
if(g[1][0] == ' '){
g[1][0] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 5:
if(g[1][1] == ' '){
g[1][1] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 6:
if(g[1][2] == ' '){
g[1][2] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 7:
if(g[2][0] == ' '){
g[2][0] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 8:
if(g[2][1] == ' '){
g[2][1] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
case 9:
if(g[2][2] == ' '){
g[2][2] = str1;
}
else{
System.out.println("Already played on that square");
}
break;
}
for(i = 0; i < 3; i ++){
for(j = 0; j < 3; j ++){
if(j == 2){
System.out.print(g[i][j]);
}
else{
System.out.print(g[i][j] + " | ");
}
n++;
}
System.out.println("");
}
System.out.print("Bye");
}
}
Hope this helps you giving an idea on how to finish it :)
Good luck
Btw here you have a Tic Tac Toe example, you can guide yourself from there. And here you have another one. Just in case you're stuck in something

How do I make a String int terminator?

So im making everyone's fun game "Rock, Paper, Scissors" I got everything working, except having the while loop repeat 3 time before stopping. Well it does repeat 3 times and stops, but the 2nd and 3rd repeat the variables don't change. Take a look at the code and tell me what I'm doing wrong.
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/**
* (Insert a brief description that describes the purpose of this method)
*
* #param args
*/
public static void main(String[] args)
{
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int input = in.nextInt();
while (count < 3)
{
compint = gen.nextInt(3) + 1;
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}
}
}
Output:
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
1
Computer: Scissors | You: Rock | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
2
Computer: Rock | You: Paper | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
Q
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at RockPaperScissors.main(RockPaperScissors.java:102)
The logic that actually does anything with the input – all those if statements – is outside of the loop. With each iteration through the look, none of that logic is not actually executed. It all just happens first. Try this instead:
for (int count=0; count < 3; count++)
{
int input = in.nextInt();
int compint = gen.nextInt(3) + 1;
// all the if statements and printing here
}
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
You're getting an InputMismatchException when typing Q but the code calls Scanner#nextInt(). The docs are pretty clear on what the problem is:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
It's basically the Scanner's way of telling you "you asked for an int but the next token isn't one." You can add an additional check before the nextInt() calls, using Scanner#hasNextInt(), to verify that the next token actually is an int. If it's not an int, then you can plan on parsing it just as a string.
So instead of this:
input = in.nextInt();
Do something like this:
if (in.hasNextInt())
{
input = in.nextInt();
} else if (in.hasNext("Q")) {
// quit
}
seems you wanted to use do - while loop
it would work:
do{
compint = gen.nextInt(3) + 1;
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int input = in.nextInt();
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}while (count < 3);

Categories

Resources