Basic Tic Tac Toe programming help please

I'm trying to make a seperate java class(there is another main that calls this using SWING interface) that makes mark on the board.
It's supposed to do the following
Method makeMark returns:
a null if the cell indicated by row and column has already been marked
an X if it is X's turn (X gets to go first)
a Y if it is Y's turn
Thus makeMark will have to keep of marks made previously and return the appropriate string
for the requested cell.
and here is what I got so far, but only getting empty clicks as a respond. Any help will be appreciated. thanks.
import javax.swing.JButton;
public class TicTacToeGame {
     public String makeMark(int row, int column){
String player = "X";
String [][] Enum = new String [3][3];
          for (row=0; row<=2; row++){
               for (column=0; column<=2; column++)
                    if (Enum[row][column] == "")
if (player == "X"){
Enum[row][column] = "X";
player = "Y";
return "X";
if (player == "Y"){
Enum[row][column] = "O";
player = "X";
return "Y";
else
return null;
          return player;
}

ok is there a simpler codes that will just flip-flop between X and O? I had it working before but somehow it's not working anymore. Before I had
public String makeMark(int row, int column){
player = "X";
if (player = "X")
player = "O";
else if (player = "O")
player = "X";
or soemthing like this but it used to work, but I had to revise the code to do more things and it stopped even flip-flopping between X and O.
Here's main code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* This class is the GUI for TicTacToe. It only handles user clicks on
* buttons, which represent X's and O's
* @author Hal Mendoza
* CSE 21 - Jan 18, 2011, 8:18:22 PM
* TicTacToe.java
public class TicTacToe extends JPanel implements ActionListener {
public final static int NUM_ROWS_COLUMNS = 3;
private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
TicTacToeGame board = new TicTacToeGame();
public TicTacToe() {
     BoxLayout ourLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
     setLayout(ourLayout);
     add(buildMainPanel());
* Builds the panel with buttons
* @return the panel with buttons
private JPanel buildMainPanel() {
     JPanel panel = new JPanel();
     GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
     panel.setLayout(gridLayout);
     for (int row = 0; row < arrayofButtons.length; ++row)
          for (int column = 0; column < arrayofButtons[0].length; ++column) {
               arrayofButtons[row][column] = new JButton();
               arrayofButtons[row][column].setPreferredSize(new Dimension(50, 50));
               arrayofButtons[row][column].addActionListener(this);
               // Use actionCommand to store x,y location of button
               arrayofButtons[row][column].setActionCommand(Integer.toString(row) + " " +
                         Integer.toString(column));
               panel.add(arrayofButtons[row][column]);
     return panel;
* Called when user clicks buttons with ActionListeners.
public void actionPerformed(ActionEvent e) {
     JButton button = (JButton) e.getSource();
     String xORo;
     String rowColumn[] = button.getActionCommand().split(" ");
     int row = Integer.parseInt(rowColumn[0]);
     int column = Integer.parseInt(rowColumn[1]);
     xORo = board.makeMark(row, column);
     if (xORo != null)
          button.setText(xORo);
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
private static void createAndShowGUI() {
     // Create and set up the window.
     JFrame frame = new JFrame("Tic Tac Toe");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     // Add contents to the window.
     frame.add(new TicTacToe());
     // Display the window.
     frame.pack();
     frame.setVisible(true);
public static void main(String[] args) {
     // Schedule a job for the event-dispatching thread:
     // creating and showing this application's GUI.
     javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
               createAndShowGUI();
}

Similar Messages

  • Help with Tic Tac Toe program....

    I am writing a tic tac toe program, and I have already put the 9 boxes onto the screen so that it looks like the Tic Tac Toe board.
    My first box looks something like this:
    Rectangle2D.Double box1 = new Rectangle2D.Double(0, 0, 100, 100);
    g2.draw(box1);
    I want assign a number to the 9 boxes so it looks like this:
    123
    456
    789
    And I want to know how am I suppose to assign a number to a box, so that when the number is pressed it will put an "X" or "O"(depending on whose turn it is).
    P.S. If you already made a Tic Tac Toe progaram can you post it so I will have an idea of what you did. thx.

    I'd hate to post the whole thing, but if you don't have access to it, here it goes:
    * @(#)TicTacToe.java     1.6 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.net.*;
    import java.applet.*;
    * A TicTacToe applet. A very simple, and mostly brain-dead
    * implementation of your favorite game! <p>
    * In this game a position is represented by a white and black
    * bitmask. A bit is set if a position is ocupied. There are
    * 9 squares so there are 1<<9 possible positions for each
    * side. An array of 1<<9 booleans is created, it marks
    * all the winning positions.
    * @version      1.2, 13 Oct 1995
    * @author Arthur van Hoff
    * @modified 04/23/96 Jim Hagen : winning sounds
    * @modified 02/10/98 Mike McCloskey : added destroy()
    public
    class TicTacToe extends Applet implements MouseListener {
         * White's current position. The computer is white.
        int white;
         * Black's current position. The user is black.
        int black;
         * The squares in order of importance...
        final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
         * The winning positions.
        static boolean won[] = new boolean[1 << 9];
        static final int DONE = (1 << 9) - 1;
        static final int OK = 0;
        static final int WIN = 1;
        static final int LOSE = 2;
        static final int STALEMATE = 3;
         * Mark all positions with these bits set as winning.
        static void isWon(int pos) {
         for (int i = 0 ; i < DONE ; i++) {
             if ((i & pos) == pos) {
              won[i] = true;
         * Initialize all winning positions.
        static {
         isWon((1 << 0) | (1 << 1) | (1 << 2));
         isWon((1 << 3) | (1 << 4) | (1 << 5));
         isWon((1 << 6) | (1 << 7) | (1 << 8));
         isWon((1 << 0) | (1 << 3) | (1 << 6));
         isWon((1 << 1) | (1 << 4) | (1 << 7));
         isWon((1 << 2) | (1 << 5) | (1 << 8));
         isWon((1 << 0) | (1 << 4) | (1 << 8));
         isWon((1 << 2) | (1 << 4) | (1 << 6));
         * Compute the best move for white.
         * @return the square to take
        int bestMove(int white, int black) {
         int bestmove = -1;
          loop:
         for (int i = 0 ; i < 9 ; i++) {
             int mw = moves;
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              int pw = white | (1 << mw);
              if (won[pw]) {
              // white wins, take it!
              return mw;
              for (int mb = 0 ; mb < 9 ; mb++) {
              if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
                   int pb = black | (1 << mb);
                   if (won[pb]) {
                   // black wins, take another
                   continue loop;
              // Neither white nor black can win in one move, this will do.
              if (bestmove == -1) {
              bestmove = mw;
         if (bestmove != -1) {
         return bestmove;
         // No move is totally satisfactory, try the first one that is open
         for (int i = 0 ; i < 9 ; i++) {
         int mw = moves[i];
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              return mw;
         // No more moves
         return -1;
    * User move.
    * @return true if legal
    boolean yourMove(int m) {
         if ((m < 0) || (m > 8)) {
         return false;
         if (((black | white) & (1 << m)) != 0) {
         return false;
         black |= 1 << m;
         return true;
    * Computer move.
    * @return true if legal
    boolean myMove() {
         if ((black | white) == DONE) {
         return false;
         int best = bestMove(white, black);
         white |= 1 << best;
         return true;
    * Figure what the status of the game is.
    int status() {
         if (won[white]) {
         return WIN;
         if (won[black]) {
         return LOSE;
         if ((black | white) == DONE) {
         return STALEMATE;
         return OK;
    * Who goes first in the next game?
    boolean first = true;
    * The image for white.
    Image notImage;
    * The image for black.
    Image crossImage;
    * Initialize the applet. Resize and load images.
    public void init() {
         notImage = getImage(getCodeBase(), "images/not.gif");
         crossImage = getImage(getCodeBase(), "images/cross.gif");
         addMouseListener(this);
    public void destroy() {
    removeMouseListener(this);
    * Paint it.
    public void paint(Graphics g) {
         Dimension d = getSize();
         g.setColor(Color.black);
         int xoff = d.width / 3;
         int yoff = d.height / 3;
         g.drawLine(xoff, 0, xoff, d.height);
         g.drawLine(2*xoff, 0, 2*xoff, d.height);
         g.drawLine(0, yoff, d.width, yoff);
         g.drawLine(0, 2*yoff, d.width, 2*yoff);
         int i = 0;
         for (int r = 0 ; r < 3 ; r++) {
         for (int c = 0 ; c < 3 ; c++, i++) {
              if ((white & (1 << i)) != 0) {
              g.drawImage(notImage, c*xoff + 1, r*yoff + 1, this);
              } else if ((black & (1 << i)) != 0) {
              g.drawImage(crossImage, c*xoff + 1, r*yoff + 1, this);
    * The user has clicked in the applet. Figure out where
    * and see if a legal move is possible. If it is a legal
    * move, respond with a legal move (if possible).
    public void mouseReleased(MouseEvent e) {
         int x = e.getX();
         int y = e.getY();
         switch (status()) {
         case WIN:
         case LOSE:
         case STALEMATE:
         play(getCodeBase(), "audio/return.au");
         white = black = 0;
         if (first) {
              white |= 1 << (int)(Math.random() * 9);
         first = !first;
         repaint();
         return;
         // Figure out the row/column
         Dimension d = getSize();
         int c = (x * 3) / d.width;
         int r = (y * 3) / d.height;
         if (yourMove(c + r * 3)) {
         repaint();
         switch (status()) {
         case WIN:
              play(getCodeBase(), "audio/yahoo1.au");
              break;
         case LOSE:
              play(getCodeBase(), "audio/yahoo2.au");
              break;
         case STALEMATE:
              break;
         default:
              if (myMove()) {
              repaint();
              switch (status()) {
              case WIN:
                   play(getCodeBase(), "audio/yahoo1.au");
                   break;
              case LOSE:
                   play(getCodeBase(), "audio/yahoo2.au");
                   break;
              case STALEMATE:
                   break;
              default:
                   play(getCodeBase(), "audio/ding.au");
              } else {
              play(getCodeBase(), "audio/beep.au");
         } else {
         play(getCodeBase(), "audio/beep.au");
    public void mousePressed(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public String getAppletInfo() {
         return "TicTacToe by Arthur van Hoff";

  • My tic-tac-toe program sucks

    If anyone has any interest, please look at this code and tell me what is wrong with it.
    It is supposed to play tic tac toe perfectly, it does not.
    I attempted to use the negamax algorithm.
    Please post any specific changes you made.
    Thanks.

    /* This doesn't seem to work, there is always at least 1 cmd line arg for some reason
    if (argc != 0)
    { printf ("WARNING: %d command line arguement(s) ignored!n", argc); }
    else
    { printf ("TEST"); }
    The reason why there is always at least one command line argument is because the name of the executable is counted.
    For example, if you ran your program like this:
    ./tic-tac-toe foo bar
    Then:
    argc == 3
    argv[0] == tic-tac-toe
    argv[1] == foo
    argv[2] == bar
    -gz

  • Tic Tac Toe--need help!

    Im making a tic tac toe game and everything works fine until you try to click the third set of blocks in order to put your X or Y in it. The program does nothing, it even seems as if the mouseDown function isnt working.......can someone help (Code below)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.lang.*;
    public class TicTacToe extends Applet {
    int test = 0;
    int test1 = 0;
    int score;
    int temp;
    char square[][];
    protected int turn;
    final int width = 117;
    boolean TurnP1;
    boolean TurnP2;
    public void init() {
    square = new char[3][3];
         for(int i = 0; i < 3; i++) {
         for(int j = 0; j < 3; j++) {
         square[i][j] = 0;
         score = 0;
         turn = 0;
         temp = 0;
         TurnP1 = false;
         TurnP2 = false;
    public void paint(Graphics g) {
         Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.black);
         for (int i = 0; i < 3; i++)
         for (int j = 0; j < 3; j++) g2.fillRect(i * width / 3, j * width / 3, 35, 35);
         drawXandO(g2);
         g2.drawString(Integer.toString(test) + " " + Integer.toString(test1), 130, 50);
    public void drawXandO(Graphics g) {
         g.setColor(Color.red);
         Font myFont = new Font("Impact", Font.PLAIN, 20);
         g.setFont(myFont);
         for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
         if (square[i][j] != 0) {
         g.drawString(" " + square[i][j] + " ", i * width / 3 + 10, j * width / 3 - 5);
    public boolean mouseDown(java.awt.Event e, int x, int y) {
    int column = (int)(x / (width / 3));
         int row = (int)(y / (width / 3)+1);
         test = column;
         test1 = row;
         turn++;
         if (square[column][row] != 0) {
         play(getCodeBase(), "beep.wav");
         if (TurnP2) {
         turn = 4;
         } else {
         turn = 3;
         return true;
         if (turn % 2 == 0) {
         //Its Player 2 turn
         TurnP1 = false;
         TurnP2 = true;
         square[column][row] = 'O';
         } else {
         //Its Player 1 turn
         TurnP1 = true;
         TurnP2 = false;
         square[column][row] = 'X';
         repaint();
    return true;

    the method you use should not be overridden without a call to the ancestor like:
    public boolean mouseDown(Event e,int x,int y){
              super.mouseDown(e,x,y);
              //your code here
    }it is more safe.but anyway the best thing to do what you want is to use:
    public MyApplet extends Applet implements MouseListener {
           public init(){
              addMouseListener(this);
          //methods mouseReleased,...
          public void mouseDown(MouseEvent e){

  • Finishing tic-tac-toe program

    Hey, so I've completed all the basic steps for playing the actual game, but now I'm working on creating the final booleans for determining if someone won or if it's a stalemate. Here's my entire code, but the boolean methods of interest are located at the bottom. Do I just use the player variable for the if statements? Am I missing anything? Thanks in advance.
    import java.util.*;
    public class Eight3
        public static void main(String[] args)
             Scanner keyboard = new Scanner(System.in);
             System.out.println("Welcome to tic-tac-toe. 'X' goes first.");
             TicTacToe newBoard = new TicTacToe();
             while(true)
             System.out.println("Enter coordinates for your move:");
             String newPlay = keyboard.nextLine();
             newBoard.play(newPlay);
             newBoard.print();
    class TicTacToe
        //will  represent the tic-tac-toe "board"
        private char[][] board;
        private char player;
        public TicTacToe()
             int row, column;
             player = 'X';
             board = new char[3][3];
             for(row = 0; row < board.length; row++)
                 for(column = 0; column < board[row].length; column++)
                     board[row][column] = ' ';
         public boolean play(String s)
              if(s.equals("A1"))
                 if(board[0][0] == ' ')
                     board[0][0] = player;
                else
                     return false;
            else if(s.equals("A2"))
                 if(board[0][1] == ' ')
                     board[0][1] = player;
                else
                    return false;
            else if(s.equals("A3"))
                 if(board[0][2] == ' ')
                     board[0][2] = player;
                else
                    return false;
            else if(s.equals("B1"))
                 if(board[1][0] == ' ')
                    board[1][0] = player;
                else
                    return false;
            else if(s.equals("B2"))
                 if(board[1][1] == ' ')
                    board[1][1] = player;
                else
                        return false;
            else if(s.equals("B3"))
                 if(board[1][2] == ' ')
                    board[1][2] = player;
                else
                    return false;
            else if(s.equals("C1"))
                if(board[2][0] == ' ')
                    board[2][0] = player;
                else
                    return false;
            else if(s.equals("C2"))
                if(board[2][1] == ' ')
                    board[2][1] = player;
                else
                    return false;
            else if(s.equals("C3"))
                     if(board[2][2] == ' ')
                         board[2][2] = player;
                else
                     return false;
            else
                 return false;
            if(player == 'X')
                 player = 'O';
            else
                player = 'X';
            return true;
        public void print()
              System.out.println("      1     2     3  ");
             System.out.println("         |     |     ");
             System.out.println("A     "+board[0][0]+"  |  "+board[0][1]+"  |  "+board[0][2]+" ");
             System.out.println("    - - - - - - - - -");
             System.out.println("B     "+board[1][0]+"  |  "+board[1][1]+"  |  "+board[1][2]+" ");
             System.out.println("    - - - - - - - - -");
             System.out.println("C     "+board[2][0]+"  |  "+board[2][1]+"  |  "+board[2][2]+" ");
             System.out.println("         |     |     ");
         public boolean won()
              if((board[0][0] == player) && (board[0][1] == player) && (board[0][2] == player))
                   return true;
              else if((board[1][0] == player) && (board[1][1] == player) && (board[1][2] == player))
                   return true;
              else if((board[2][0] == player) && (board[1][1] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][0] == player) && (board[1][0] == player) && (board[2][0] == player))
                   return true;
              else if((board[0][1] == player) && (board[1][1] == player) && (board[2][1] == player))
                   return true;
              else if((board[0][2] == player) && (board[1][2] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][0] == player) && (board[1][1] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][2] == player) && (board[1][1] == player) && (board[2][0] == player))
                   return true;
              else
                   return false;
         public boolean stalemate()
              //not sure about this
    }

    Sorry about the ugliness - no it doesn't do what I want it to yet - I would just like some assistance with the public boolean won() method. The game doesn't end when a real life winner is determined. So, if we could just start with that, that'd be great. Thanks.

  • Powershell tic tac toe programming

    Hey guys, I've got a little question, I'm working on a little game since some time now, and I have a little problem. I need to get the color of a button. Let me explain:
    Instead of crosses and circles, I'm using colors for my tic tac toe (or Noughts and crosses dunno how you call it) and I need to get the color of the buttons so I can program the computer to have his plays based on mine, have you got any idea?

    Try this. It works just fine:
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $button1 = New-Object 'System.Windows.Forms.Button'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    #endregion Generated Form Objects
    $button1_Click={
    if($button1.BackColor -eq 'red'){$button1.BackColor='blue'}else{$button1.BackColor='red'}
    $Form_StateCorrection_Load=
    #Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
    $Form_Cleanup_FormClosed=
    #Remove all event handlers from the controls
    try
    $button1.remove_Click($button1_Click)
    $form1.remove_Load($FormEvent_Load)
    $form1.remove_Load($Form_StateCorrection_Load)
    $form1.remove_FormClosed($Form_Cleanup_FormClosed)
    catch [Exception]
    $form1.SuspendLayout()
    $form1.Controls.Add($button1)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.ClientSize = '438, 262'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = "form1"
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = "Form"
    # button1
    $button1.BackColor = 'Red'
    $button1.Location = '197, 55'
    $button1.Name = "button1"
    $button1.Size = '75, 23'
    $button1.TabIndex = 1
    $button1.Text = "button1"
    $button1.UseVisualStyleBackColor = $False
    $button1.add_Click($button1_Click)
    # buttonOK
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '351, 227'
    $buttonOK.Name = "buttonOK"
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = "&OK"
    $buttonOK.UseVisualStyleBackColor = $True
    $form1.ResumeLayout()
    #endregion Generated Form Code
    $InitialFormWindowState = $form1.WindowState
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    $form1.ShowDialog()
    ¯\_(ツ)_/¯

  • Tic Tac Toe code Help

    I am a beginner Java programmer, and I need help with my tic tac toe code.
    import javax.swing.JOptionPane;
    * Created on Nov 14, 2006
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author jye
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class TicTacToe {
        public static void main(String[] args) {
            int[][]matrix = {{0,1,2},{3,4,5},{6,7,8}};
            while (true)
            System.out.println(); //keeps the tables seperate
            for(int row = 0; row<matrix.length;row++)
                for(int col = 0; col < matrix[row].length;col++)
                if (matrix[row][col]!=-1 && matrix[row][col]!=-2) //Compares each element to -1 and and -2, if not, then it just prints out the regular number
                System.out.print(matrix[row][col] + " ");
                if (matrix[row][col]==-1)
                    System.out.print("X" + " ");
                if (matrix[row][col]==-2)
                System.out.print("O" + " ");
                System.out.println();
                int p1 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 1"));
                int p2 = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number 2"));
            for(int row = 0; row<matrix.length;row++) //this piece of code refers to above print code
                for(int col = 0; col < matrix[row].length;col++)
                if (p1==matrix[row][col]) //compares each element in array to the position inputted. If it is equal to the number inputted, then it changes that to -1. For example, the postition of 4 is [1][1], it will replace [1][1] with -1. The matrix[row][col] is a position.
                    matrix[row][col]=-1;
                if(p2==matrix[row][col])
                    matrix[row][col]=-2;
            for(int row = 0; row<matrix.length;row++)
                for(int col = 0; col < matrix[row].length;col++)
                    if(matrix[0][0]==-1 && matrix[0][1]==-1 && matrix[0][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[1][0]==-1 && matrix[1][1]==-1 && matrix[1][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[2][0]==-1 && matrix[2][1]==-1 && matrix[2][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][0]==-1 && matrix[1][0]==-1 && matrix[2][0]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][1]==-1 && matrix[1][1]==-1 && matrix[2][1]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][2]==-1 && matrix[1][2]==-1 && matrix[2][2]==-1)
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][0]==-1 && matrix[1][1]==-1 && matrix[2][2]==-1);
                        System.out.println("Player 1 wins.");break;
                    if(matrix[0][2]==-1 && matrix[1][1]==-1 && matrix[2][0]== -1)
                        System.out.println("Player 1 wins.");break; //I GET A "UNREACHEABLE CODE" ERROR HERE
                    if(matrix[0][0]==-2 && matrix[0][1]==-2 && matrix[0][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[1][0]==-2 && matrix[1][1]==-2 && matrix[1][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[2][0]==-2 && matrix[2][1]==-2 && matrix[2][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][0]==-2 && matrix[1][0]==-2 && matrix[2][0]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][1]==-2 && matrix[1][1]==-2 && matrix[2][1]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][2]==-2 && matrix[2][2]==-2)
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
                        System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
    }Why do I get a unreachable error code???
    Thanks.

    Just in case you are tired I mean this (from the ending bit of your code)
    if(matrix[0][0]==-2 && matrix[1][1]==-2 && matrix[2][2]==-2);// <== PROBLEM RIGHT HERE
                        System.out.println("Player 2 wins.");break;
                    if(matrix[0][2]==-2 && matrix[1][1]==-2 && matrix[2][0]== -2)
                        System.out.println("Player 2 wins.");break;//I GET A "UNREACHEABLE CODE" ERROR HERE
                    }And same earlier on.

  • Tic Tac Toe Java help!

    Hi, I have been trying to create a simple Tic Tac Toe game using Java. I'm currently having problems as to how to create the board using arrays (sorry I don't understand them very well). All I have so far is this,
    public class ticTacToe {
    private int [] [] theBoard = new int [3] [3];
         // *'N' is no winner
         // 'X' is X won
         // 'O' is O won
         // 'C' is a cat's game
         public static char didSomeoneWin(int [] [] currentBoard)
              int winForX = 8000, winForO = 1, checkIfItsAcatsGame = 1, product;
              char winner = 'N';
              for(int column = 0; column < 3; column++) // Check the columns
                   product = currentBoard [0] [column] * currentBoard [1] [column] * currentBoard [2] [column];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              for(int row = 0; row < 3; row++) // Check the rows
                   product = currentBoard [row] [0] * currentBoard [row] [1] * currentBoard [row] [2];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              product = currentBoard [0] [0] * currentBoard [1] [1] * currentBoard [2] [2]; // Check one diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              product = currentBoard [0] [2] * currentBoard [1] [1] * currentBoard [2] [0]; // Check the other diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              if(winner == 'N') // If nobody's won, Check for a cat's game
                   for(int row = 0; row < 3; row++)
                        for(int column = 0; column < 3; column++)
                             checkIfItsAcatsGame *=currentBoard [row] [column];
                   if(checkIfItsAcatsGame != 0) winner = 'C'; // any empty space is a zero. So product is zero if there is space left.
              return winner;
         public void markX(int row, int column)
              myBoard [row] [column] = 20;
         public void markO(int row, int column)
              myBoard [row] [column] = 1;
    That is all so far, could someone help me print out the board? And help me out on the arrays? I don't think they are quite right. Thanks in Advance!
    Message was edited by:
    matthews1.7.2.0

    Hi,
    Do you need a GUI ?
    If yes see http://java.sun.com/docs/books/tutorial/uiswing/index.html
    You can also see this : http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html about printing.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Tic tac toe pls help! there is clarification

    How can i build a tic tac toe game in labview
    What im interested in is the following, and ive added an image of what the front panel should look like with some clarification
    1) A 3x3 multiplayer game
    2) A boolean to move left in the tictactoe grid and another to move down
    3) A boolean array to display the grid an another string array to show the X and O's
    4) A boolean to confirm player's choice
    5) A way to choose whether player 1 or player 2 begins
    6) A way to show which player wins or loses, or if it is a draw.
    Thank You in Advance
    I appreciate your help !!
    Attachments:
    3.JPG ‏58 KB

    You have already asked the question here.
    You still have to prove that this isn't homework. 

  • Tic Tac Toe Program

    I want to write a tic tac toe applet that draws a game board and then accepts mouseclicks into the squares. It automatically changes players after each turn and declares a winner at the end.
    I figured out how I might do this by using a JFrame with a grid layout of buttons in a panel (i.e. click buttons and their labels change?).
    But how would I go about doing it without using buttons. I need to create a grid of squares that accept mouse clicks. I also need to be able to proclaim a winner based upon a winning pattern.
    Any ideas? Could you just point me in the right direction?
    How would the grid be generated? (A series of rectangle objects? Lines?)
    How would I actually place a letter (x or o) in a square. ( some calculating of bounding coordinates for each box?)
    Thanks!!

    each square could be a jpanel. write a class called Square, that extends jpanel.
    implement MouseListener... and that's about it. It will just be a state machine.
    In your main class, make a 2d array of Squares...
    not really difficult.

  • TIC TAC TOE Programming Issue

    Somehow I only have the X's in the i=j or i+j=2 boxes and O's in all the other. Anybody know what's the problem and I can't get it to repeat 3 times...i tried doing the do while loop
       public void actionPerformed( ActionEvent e )
         int i=0;
         int j=0;
         int turn = 0;
         int currentGame = 1;
         boolean winner;
         boolean found = false; //Search for button in 2-D array
         char winChar = ' '; //Hold winner's symbol
         showStatus("");
         for(i=0; i<ROW; ++i)
            for(j=0; j<COL && !found; ++j)
               //Sets X to all the odd turns
               if(turn%2==1 && e.getSource()==ttt[i][j])
                                          //Which button was pressed?
                  ttt[i][j].setBackground(Color.red); //Red X
                  ttt[i][j].setFont(tttFont); //Set to 48 pt bold font
                  ttt[i][j].setText("X"); //Assign 'X' to odd play
                  ttt[i][j].setEnabled(false); //Disable button
                  winChar = 'X'; //Assign symbol
                  found = true;
               //Sets O to all the even turns
               if(turn%2==0 && e.getSource()==ttt[i][j])
                  ttt[i][j].setBackground(Color.blue); //Blue O
                  ttt[i][j].setFont(tttFont); //Set to 48 pt bold font
                  ttt[i][j].setText("O"); //Assign 'O' to even play
                  ttt[i][j].setEnabled(false); //Disable button
                  winChar = 'O'; //Assign symbol
                  found = true;
            ++turn;
         if( winner = isAWin(winChar) ) //Game has a winner
            for(i=0; i<ROW; ++i) //Resets game
               for(j=0; j<COL; ++j)
                  ttt[i][j].setBackground(Color.white);
                  ttt[i][j].setText(""); //Clear buttons
                  ttt[i][j].setEnabled(true); //Enable buttons
            if(currentGame<3)
               showStatus("WINNER of GAME #" + currentGame + ":" + winChar);
               games[currentGame] = winChar; //Store winner in 1-D array
            else
               showStatus("WINNERS: #1:" + games[1] + "#2:" + games[2] + "#3:" +
                          winChar);
            ++currentGame;
       }

    Well, it looks like you've fairly comprehensively misunderstood the events model of swing.
    An actionPerformed is called for each mouse click so you certainly shouldn't be intialising stuff like turn numbers etc in one.
    Rather than using one actionPerformed, presumably defined as part of the JFrame, create a new ActionListener object for each button which knows that block's coordinates so you don't have to muck about searching for the block which you clicked on. Create an inner class which implements ActionListener and create a separate instance for each block (I assume they are JButtons).
    And it's likely to look better if you use ImageIcons for your symbols, not character strings.

  • NEED TIC TAC TOE HELP

    Why do I keep getting the following errors in a very simple, basic TIC TAC TOE program? Any help would be greatly appreciated. Thanks.
    C:\Class\Teresa\TicTacToe017.java:114: 'else' without 'if'
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    ^
    C:\Class\Teresa\TicTacToe017.java:185: 'else' without 'if'
    else // Next player's turn
    ^
    C:\Class\Teresa\TicTacToe017.java:39: cannot resolve symbol
    symbol : method call ()
    location: class TicTacToe017
                        call();
    ^
    C:\Class\Teresa\TicTacToe017.java:145: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:165: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:181: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    6 errors
    Tool completed with exit code 1
    Here is my code so far.
    File name: TicTacToe.java
    A class to play TicTacToe.
    Entries cannot be changed once they are entered.
    Written by: Lew Rakocy
    email address: [email protected]
    Date: 9/2/00
    Changes: 03/13/2003 Made comments like text examples.
    Added code to display board after win and draw.
    public class TicTacToe017
    // Use a 3 X 3 (two-dimensional) array for the game board.
    private static char[][] board = new char[3][3];
    private static char turn;
    private static int row; // Loop controls to
    private static int col; // display the board
    private static int turnRow; // User input to
    private static int turnCol; // select move
    private static boolean entryError;
    private static boolean anotherGame = true;
    private static char repeat; // User input: y or Y to repeat
    private static int entryCount = 0; // Game ends when board is full
    // (when entryCount = 9);
    public static void main(String[] args)
    while(anotherGame)
    newGame();
    while(!winner())
                        //WRITE THE METHOD CALL TO DISPLAY THE "BOARD" HERE
                        call();
                        System.out.println("This is the game board.");
    //WRITE THE METHOD CALL FOR THE "PLAY" OF THE GAME HERE
                        System.out.print("Welcome to Teresa's Tic Tac Toe!");
    System.out.println("Another game? Enter Y or y for yes.");
    repeat = SavitchIn.readLineNonwhiteChar();
    //WRITE THE IF/ELSE STATEMENT TO PLAY ANOTHER GAME HERE
    if ((repeat == 'Y') || (repeat == 'y'))
         System.out.println("Play another game.");
    else
         System.out.println("End of game. Thanks for playing.");
    //WRITE THE HEADER FOR THE writeBoard METHOD HERE
    System.out.println("-----------------");
    System.out.println("|R\\C| 1 | 2 | 3 |");
    System.out.println("-----------------");
    for(row = 0; row < 3; ++row)
    System.out.println("| " + (row + 1)
    + " | " + board[row][0]
    + " | " + board[row][1]
    + " | " + board[row][2]
    + " |");
    System.out.println("-----------------");
    private static void getMove()
    entryError = true; // Will change to false if valid row
    // and column numbers are entered.
    while(entryError)
    System.out.println();
    System.out.println(turn + "'s turn.");
    System.out.println("Where do what your " + turn + " placed?");
    System.out.println(
    "Please enter row number and column number"
    + " separated by a space.");
    System.out.println();
    turnRow = SavitchIn.readInt();
    turnCol = SavitchIn.readInt();
    System.out.println("You have entered row #" + turnRow);
    System.out.println(" and column #" + turnCol);
    // Check for proper range (1, 2, or 3)
                   //WRITE THE IF STATEMENT HERE FOR AN INVALID ENTRY
                   if (board[turnRow - 1][turnCol - 1] > 3)
              System.out.println("Invalid entry: try again.");
    System.out.println(
    "Row & column numbers must be either 1, 2, or 3.");
    // Check to see if it is already occupied
    // Adjust turnRow and turnCol for 0-numbering in array
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    || board[turnRow - 1][turnCol - 1] == 'O')
    System.out.println("That cell is already taken.");
    System.out.println("Please make another selection.");
    else // Valid entry
    entryError = false;
    System.out.println("Thank you for your selection.");
    board[turnRow - 1][turnCol - 1] = turn;
    ++entryCount;
    private static boolean winner()
    // Row checks
    for(row = 0; row < 3; ++row)
    if(board[row][0] == turn)
    if(board[row][1] == turn)
    if(board[row][2] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // WRITE A FOR LOOP FOR THE COLUMN CHECKS HERE
    // WRITE A FOR LOOP FOR THE DIAGONAL CHECKS HERE
    if(board[0][2] == turn)
    if(board[1][1] == turn)
    if(board[2][0] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // These lines execute only if there is no winner.
    // End game if board is full
    //WRITE THE IF STATEMENT TO CHECK IF THE BOARD IS FULL
              if (entryCount == 9)
    System.out.println();
    System.out.println("Draw: no winner and board is full.");
    writeBoard();
    return true;
    else // Next player's turn
    //WRTITE THE IF/ELSE STATEMENT FOR THE NEXT PLAYER'S TURN
    return false;
    private static void newGame()
    System.out.println();
    System.out.println("New Game: X goes first.");
    turn = 'O'; // Turn will change to X when winner() is called
    // Clear the board
    for(row = 0; row < 3; ++row)
    for(col = 0; col < 3; ++col)
    board[row][col] = ' ';
    entryCount = 0;
    System.out.println();

    the "else without if" means that you have an else statement that wasn't attached to an if statement. In your case, it seems to be because you had multiple statements following an if statement, and you didn't enclose them in a single block.
    The "cannot resolve symbol" means that you referred to something that wasn't defined. Either it's your code, and you forgot to define it, or you were referring to someone else's code, in which case you probably forgot an import statement, or you're using their code incorrectly.

  • Tic - Tac - Toe Game - Please Help!

    Hi everyone, I am attempting to create a tic - tac - toe game (O's & X's).
    I would like there to be two playing modes to the game, the first mode will be one player where the user plays against the computer. The second mode is a two - player game, where two users play, one being X's and the other being O's.
    Can anyone help me get started with this game, I know there is source code on the internet but I would rather not use this as I would like to learn as I create the game.
    Thanks Everyone

    its amazing how much code a simple game like tic-tac-toe can require.. well, only if you program the AI of the computer.. i wrote one in c++ last year, for my computer science class, and the whole class had trouble with it, mainly the AI.. a suggestion to you: write it in an object-oriented manner. i ended up writing it procedurally and in the end, it looked very bad, but it worked!
    i would prob. setup some objects like: Board (the 3x3 grid), Mark (a user mark, such as an "x" or an "o")..
    i dunno.. hope that helps some, if you need help with the AI at all.. i do have the tic-tac-toe program i wrote on my website (http://www.angelfire.com/blues/smb/ ) in the C++ section.. i used a graphics package, but the logic is all there and the code is well commented.
    anyway, ill talk to ya later, good luck,
    Steven Berardi

  • Help with tic tac toe

    hey all,
    i am having problems creating a tic tac toe program. the program should create a board with NxN spaces, where N is obtained through user input.
    I created a fully working program that does a 3x3 board, checks for diagonal, vertical, horizontal wins and also allows 1 vs computer or 2 players play, but i am struggling with the NxN board.
    here is the code of what i have, can anyone point me in the right direction? all help is appreciated! please keep it simple as possible as i am just learning java!!
    import java.util.Scanner;
    import java.util.Random;
    public class NoughtsCrosses
    static final String PLAYER1 = "X";
    static final String PLAYER2 = "O";
    static final String EMPTY = "�";
    static String[][] board = new String[][];
    static int turn = 0;
    static public void makeBoard(int boardSize)
    for (int x = 0; x < boardSize; x++)
    for (int y = 0; y < boardSize; y++)
    board[x][y] = new String(EMPTY);
    static public void playComputer()
    Scanner scan = new Scanner(System.in);
    Random generator = new Random();
    int move;
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    System.out.print("Make a Move: ");
    move = scan.nextInt();
    else
    System.out.print("Computer, place your O: ");
    move = generator.nextInt(10);
    System.out.println(move);
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void playHuman()
    Scanner scan = new Scanner(System.in);
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    else
    System.out.println("Player 2, place your O");
    System.out.print("Make a Move: ");
    int move = scan.nextInt();
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void getMove(int move)
    int row = move/3;
    int col = move%3;
    if (board[row][col].equals(EMPTY))
    board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
    turn++;
    else
    System.out.println("OCCUPIED FIELD! TRY AGAIN!");
    static public void printBoard()
    for (int x = 0; x < 3; x++)
    for (int y = 0; y < 3; y++)
    if(y == 0)
    System.out.print(" ");
    System.out.print(board[x][y]);
    if(y < 2)
    System.out.print(" | ");
    System.out.println();
    if(x < 2)
    System.out.println(" ---|---|---");
    static public String winner()
    for (int i = 0; i < board.length; i++)
    /** check horizontally */
    if (board[0].equals(board[i][1]) && board[i][0].equals(board[i][2]))
    if (!board[i][0].equals(EMPTY))
    return board[i][0];
    /** check vertically */
    if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]))
    if (!board[0][i].equals(EMPTY))
    return board[0][i];
    /** check diagonally */
    if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]))
    if (!board[0][0].equals(EMPTY))
    return board[0][0];
    if (board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]))
    if (!board[0][2].equals(EMPTY))
    return board[0][2];
    return EMPTY;
    static public void main(String[] args)
    Scanner scan = new Scanner(System.in);
    int boardSize;
    System.out.println();
    System.out.println("Welcome to Tic Tac Toe!");
    System.out.println("�����������������������");
    System.out.println("How big should the board be?");
    boardSize = scan.nextInt();
    makeBoard(boardSize);
    int players = 0;
    do{
    System.out.println("How many players?");
    System.out.println("1 (vs. Computer) or 2 (vs. another player)?");
    players = scan.nextInt();
    System.out.println();
    }while(players < 1 || players > 2);
    if (players == 1)
    playComputer();
    else
    playHuman();

    well, i figured out how to do it all, thanks to the TREMENDOUS amount of help here...lol...
    i just have one more (minor problem)...
    i can't get an algorithm working to see if the two diagonals are occupied by x's or o's (see if someone won diagonally)
    to check horizontally & vertically on an NxN board, i use following code:
    int count = 0;
            /** check horizontally  */
            for (int i = 0; i < myBoard.length; i++)
               for (int j = 0; j < myBoard.length-1; j++)
                   if (myBoard[0].equals(myBoard[i][j+1]) && !myBoard[i][0].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[i][0];
    count = 0;
    count = 0;
    /** check vertically */
    for (int i = 0; i < myBoard.length; i++)
    for (int j = 0; j < myBoard.length-1; j++)
    if (myBoard[j][0].equals(myBoard[j+1][i]) && !myBoard[0][i].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[0][i];
    count = 0;
    now i was messing around ALOT and couldn't figure out how to get the diagonals showing! this is what i came up with:
    count =0;
    for (int j = 1; j < myBoard.length; j++)
           if (myBoard[0][0].equals(myBoard[j][j]) && !myBoard[0][0].equals(EMPTY))
                 count++;
                 System.out.println(count);
            if (count >= myBoard.length)
                 return myBoard[0][0];
    count = 0;
    for (int j = myBoard.length-1; j >= 0; j--)
         if (myBoard[0][myBoard.length-1].equals(myBoard[j][j]) && !myBoard[0][myBoard.length-1].equals(EMPTY))
             count++;
             System.out.println(count);
          if (count >= myBoard.length)
              return myBoard[0][myBoard.length-1];
          count = 0;

  • Need some help with Tic Tac Toe game

    hey. hope u guys can help me out...
    having a problem with my tic tac toe program...
    i have 2 problems.
    1) got the "X" and "O" to appear using a flag(teacher didn't explain)
    using code like this
    if (jb == button[0]){
    if (flag==0)
    button[0].setText("X");
    else
    button[0].setText("O");
    //toggle
    flag = (flag==0)?1:0;
    my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
    2) found this code in javascript online and i want to do what it does in java code
    if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
    alert("You Win!");
    reset();
    how would i do that?
    thanks for the help.

    ok here's my code:
    //TTT.java
    import javax.swing.*;
    import java.awt.*;
    import java .awt.event.*;
    public class TTT extends JFrame
                        implements WindowListener, ActionListener
    private JFrame frFirst;
    private Container cnFirst,cnSecond;
    private     JButton button[]=new JButton[9];
    private JButton btnNewGame,btnExit;
    private FlowLayout southLayout;
    private JPanel southPanel;
    private int flag;
    public TTT()
                   frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
                   cnFirst=frFirst.getContentPane();
                   cnFirst.setLayout (new GridLayout (4,4));
                   cnFirst.setBackground(Color.green);
              for(int i=0;i<button.length;i++)
                        button[i] = new JButton();
                        cnFirst.add(button);
                        flag=0;
              southPanel = new JPanel ();
              btnNewGame = new JButton ("New Game");
              southPanel.add (btnNewGame);
              btnExit = new JButton ("EXIT");
              southPanel.add (btnExit);
              frFirst.add (southPanel,BorderLayout.SOUTH);
              frFirst.setLocation(200, 200);
              frFirst.setSize(400,400);
              frFirst.setResizable(false);
              frFirst.setVisible(true);
              this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // listeners
                   frFirst.addWindowListener(this);
                   button[0].addActionListener(this);
                   button[1].addActionListener(this);
                   button[2].addActionListener(this);
                   button[3].addActionListener(this);
                   button[4].addActionListener(this);
                   button[5].addActionListener(this);
                   button[6].addActionListener(this);
                   button[7].addActionListener(this);
                   button[8].addActionListener(this);
                   btnNewGame.addActionListener (this);
                   btnExit.addActionListener (this);
         //define methods of WindowListener
    public void windowOpened(WindowEvent we)
         public void windowClosing(WindowEvent we)
         System.exit(0);
         public void windowClosed(WindowEvent we)
         public void windowIconified(WindowEvent we)
         public void windowDeiconified(WindowEvent we)
         public void windowActivated(WindowEvent we)
         public void windowDeactivated(WindowEvent we)
    public void actionPerformed(ActionEvent ae)
    //making the X and O to appear on JButtons
         Object obj = ae.getSource();
              if (obj instanceof JButton){
                   JButton jb = (JButton)obj;
                   if (jb == button[0])
                        if (flag==0)
                        button[0].setText("X");
                   else
                        button[0].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[1])
                        if (flag==0)
                        button[1].setText("X");
                   else
                        button[1].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[2])
                        if (flag==0)
                        button[2].setText("X");
                   else
                        button[2].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[3])
                        if (flag==0)
                        button[3].setText("X");
                   else
                        button[3].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[4])
                        if (flag==0)
                        button[4].setText("X");
                   else
                        button[4].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[5])
                        if (flag==0)
                        button[5].setText("X");
                   else
                        button[5].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[6])
                        if (flag==0)
                        button[6].setText("X");
                   else
                        button[6].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[7])
                        if (flag==0)
                        button[7].setText("X");
                   else
                        button[7].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[8])
                        if (flag==0)
                        button[8].setText("X");
                   else
                        button[8].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
    //New Game To Reset
              if (ae.getSource () == btnNewGame)
    /*     String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
    String YES;
    if (text == YES)
         JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
         else{
    add code to reset game
         //Exit Button to Exit
         if (ae.getSource () == btnExit)
              JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
              this.setVisible(false);
         System.exit(0);
              }     //end of if instanceof
    public static void main(String[]args)
         //instantiate GUI
         new TTT();

Maybe you are looking for

  • I reset my ipod shuffle gen 2 successfully but it still isn't recognized by itunes

    I downloaded iPod Reset Utility and according to the app, my iPod shuffle was reset successfully.  However, it still isn't showing up in my finder and iTunes says it can't recognize the ipod until it is reset.  Also, the lights don't go on.  Battery

  • How to get the first letter alone in Upper case?

    SQL*Plus: Release 9.2.0.1.0 - Production on Thu Jan 15 11:13:44 2009 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production With the Partitioning,

  • PHP MySql connection to GoDaddy

    I use DWCS4, PHP, MySQL. I have created a MySql database on my GoDaddy-hosted account and can FTP to it and have transferred tables and data to it. However, when I try to create a database connection in DW, I get the following error message; "Your PH

  • I need to find out my balance or my iTunes account. How do I find out on my iPhone 4s?

    How do I find out on my iPhone 4s? I wanna buy a 10$ iTunes card but need to know if my negative balance is more or less than 10$

  • Custom Infotype error in upgrade.

    Hi, We did a upgrade from 4.6C to 5.0. When we are doing syntax check for one of the program which has used custom infotype 9002 it is giving following error "Include report "%_HR9002" not found." What could be the reason for this ?