Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Replacing an If statement with a Switch statement

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Location
    UK
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Replacing an If statement with a Switch statement

    Can anyone help me improve my code please?
    I have created this tic-tac-toe applet in university and I have been asked to try and replace some of the if statements with switch statements.

    But I am unsure which set of if statements would be more suitable as a switch.
    An I do not have a lot of experience with switch statements, I have only been using Java for 2 months.

    Here is my code. If anyone can suggest which set of if statements would be more suitable as a switch statement I would really appreciate it.

    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*;  
     
    public class TicTacToe extends JApplet implements  ActionListener{    
     
    	JButton squares[];    
    	JButton newGameButton;  
    	JLabel score;  
    	JLabel wins;  
    	JLabel loses;
    	JLabel ties;
    	int emptySquaresLeft=9;  
    	int gamesWon=0;  
    	int gamesLost=0;
    	int gamesTied=0;
     
    	//Declares the colours that will be used,  using the RGB values
    	Color bgColour = new Color(30, 114, 165); // Medium blue
    	Color squareColour = new Color(252, 248, 163); // Light yellow
     
    public static void main(String[] args) { 
     
    	//... Create an initialize the applet.     
    	JApplet theApplet = new TicTacToe();     
    	theApplet.init();         // Needed if overridden in applet     
    	theApplet.start();        // Needed if overridden in applet 
     
    	//... Create a window (JFrame) and make applet the content pane.    
    	JFrame window = new JFrame("Tic Tac Toe Applet and Application");     
    	window.setContentPane(theApplet);     
    	window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
     
    	// Arrange the components.     
    	window.setSize(300,300); 	// Sets the window size    
    	window.setVisible(true);    // Make the window visible
    	}  
     
    	//======================================== Applet constructor 
     
    	public TicTacToe() {     
    		add(new JLabel("This is both an Applet and Application!"));
    		}
    	/**
    	 * init method is the applet's constructor  
    	 */   
    	public void init(){  
     
    		// Get the applet's content pane -   
    		// all window components go there  
    		Container  appletContent = this.getContentPane();  
    		resize(400,400); 
     
    		//Set the applet's layout manager, font and background color  
    		appletContent.setLayout(new BorderLayout());  
    		appletContent.setBackground(bgColour);     
     
    		// Create the button New Game and register it   
    		// with the action listener   
    		newGameButton=new JButton("New Game");  
    		newGameButton.addActionListener(this);  
     
    		// Creates the won, lost and ties labels
    		wins=new JLabel("Won: ");  
    		loses=new JLabel("Lost: ");
    		ties=new JLabel("Ties: ");
     
    		// Creates the top panel and adds the new game button to the North
    		JPanel topPanel=new JPanel();  
    		topPanel.setLayout(new BorderLayout());
    		topPanel.add(newGameButton,"North"); 
     
    		// Creates the top lower panel, sets the colour and grid layout
    		JPanel topLowerPanel=new JPanel();
    		topLowerPanel.setLayout(new GridLayout(1,0));
    		topLowerPanel.setBackground(bgColour);
     
    		// Adds the wins label to the panel
    		topLowerPanel.add(wins);  
    		Font labelFont = wins.getFont();
    		wins.setFont(new Font(labelFont.getFontName(), labelFont.getStyle(), 16));
    		wins.setForeground(Color.WHITE);
     
    		// Adds the loses label to the panel
    		topLowerPanel.add(loses);
    		loses.setFont(new Font(labelFont.getFontName(), labelFont.getStyle(), 16));
    		loses.setForeground(Color.WHITE);
     
    		// Adds the ties label to the panel
    		topLowerPanel.add(ties);
    		ties.setFont(new Font(labelFont.getFontName(), labelFont.getStyle(), 16));
    		ties.setForeground(Color.WHITE);
     
    		// Adds the top lower panel to the center of the top panel
    		topPanel.add(topLowerPanel,"Center");  
    		// Adds the top panel to the North of the applet content
    		appletContent.add(topPanel,"North");
     
    		//Creates the center panel
    		JPanel centerPanel=new JPanel();  
    		centerPanel.setLayout(new GridLayout(3,3)); 
    		// Adss the center panel to the Center of the applet content
    		appletContent.add(centerPanel,"Center"); 
     
    		// Gets the current font style of the score and sets the font size to 16
    		//Creates the score label an adds it to the bottom of the interface
    		score=new JLabel("Your turn!");  
    		score.setForeground(squareColour);
    		score.setFont(new Font(labelFont.getFontName(), labelFont.getStyle(), 16));
    		appletContent.add(score,"South");       
     
    		// create an array to hold references to 9 buttons  
    		squares=new JButton[9];         
     
    		// Instantiate the buttons, store the references   
    		// to them in the array, register them with the   
    		// listeners, paint them in orange and add to panel   
    		for(int i=0;i<9;i++){    
    			squares[i]=new JButton();    
    			squares[i].addActionListener(this);
    			squares[i].setBackground(squareColour); 
     
    			// Gets the current font style of the squares and sets the font size to 36
    			Font currentFont = squares[i].getFont();
    			squares[i].setFont(new Font(currentFont.getFontName(), currentFont.getStyle(), 36));
    			centerPanel.add(squares[i]);     
     
    			// Create the the frame and set it's content pane        
    			JFrame frame = new JFrame("TicTacToe");      
    			}  
    	}   
    	/**  
    	 * This method will process all action events  
    	 * @param ActionEvent object  
    	 */  
    	public void actionPerformed(ActionEvent e) {   
    		JButton theButton = (JButton) e.getSource();  
     
    		// Is this a New Game button?  
    		if (theButton ==newGameButton){   
    			for(int i=0;i<9;i++){    
    				squares[i].setEnabled(true);    
    				squares[i].setText("");    
    				squares[i].setBackground(squareColour);   
    				}      
    			emptySquaresLeft=9;     
    			score.setText("Your turn!");     
    			newGameButton.setEnabled(false); 
    			   return;  // exit the method here    
    			   }       
    		String winner = "";  
     
    		// Is this one of the squares?        
    		for ( int i=0; i<9; i++ ) {       
    			if (  theButton == squares[i] ) {         
    				squares[i].setText("X");         
    				squares[i].setEnabled(false);                           
    				winner = lookForWinner();          
    				if(!"".equals(winner)){             
    					endTheGame();                      
    					} else {             
    						computerMove();             
    						winner = lookForWinner();   
    						if ( !"".equals(winner))             
    						{               
    							endTheGame();             
    							}         
    						}        
    				break;         
    				}     
    			} 
    		// end loop  
    		if ( winner.equals("X") ) {   
    			score.setText("You won!");
     
    			// increment win counter  
    			gamesWon+=1;
    			wins.setText(" Won: " +gamesWon);     
    			} else if (winner.equals("O")){   
    				score.setText("You lost!"); 
     
    				// increment lost counter  
    				gamesLost+=1;  
    				loses.setText(" Lost: "+gamesLost);  
    				} else if (winner.equals("T")){     
    					score.setText("It's a tie!");
     
    					// increment tie counter  
    					gamesTied+=1;
    					ties.setText(" Ties: " +gamesTied); 
    					}   
    		} // end actionPerformed   
    	/**  
    	 *  This method is called after every move to see   
    	 *  if we have a winner.   
    	 *  It checks every row, column and diagonal to find out   
    	 *  three squares with the same label (other than blank)  
    	 *  @return "X", "O", "T" for tie or "" for no winner       
    	 */   
     
    	String lookForWinner() {      
    		 String theWinner = "";     
    		 emptySquaresLeft--;          
    		 if (emptySquaresLeft==0){ 
    			 return "T";  // it's a tie     
    			 }         
    		 // Check the row 1 - array elements 0,1,2       
    		 if (!squares[0].getText().equals("") & squares[0].getText().equals(squares[1].getText()) & squares[0].getText().equals(squares[2].getText()) ) {  
    			 theWinner = squares[0].getText();          
    			 highlightWinner(0,1,2);     
    		 }
    			 // Check the row 2  - array elements 3,4,5     
    			 if (!squares[3].getText().equals("") & squares[3].getText().equals(squares[4].getText()) & squares[3].getText().equals(squares[5].getText()) ) {  
    				 theWinner = squares[3].getText();       
    				 highlightWinner(3,4,5);    
    			 }
    				 // Check the row 3 -  - array elements 6,7,8      
    				 if (!squares[6].getText().equals("") & squares[6].getText().equals(squares[7].getText()) & squares[6].getText().equals(squares[8].getText()) ) {  
    					 theWinner = squares[6].getText();         
    					 highlightWinner(6,7,8);  
    				 }
    					 // Check the column 1  - array elements 0,3,6     
    					 if (!squares[0].getText().equals("") & squares[0].getText().equals(squares[3].getText()) & squares[0].getText().equals(squares[6].getText()) ) {  
    						 theWinner = squares[0].getText();         
    						 highlightWinner(0,3,6);   
    					 }
    						 // Check the column 2 - array elements 1,4,7
    						 if (!squares[1].getText().equals("") & squares[1].getText().equals(squares[4].getText()) & squares[1].getText().equals(squares[7].getText()) ) {  
    							 theWinner = squares[1].getText();          
    							 highlightWinner(1,4,7);	
    						 }
    							 // Check the column 3 - array elements 2,5,8 
    							 if (!squares[2].getText().equals("") & squares[2].getText().equals(squares[5].getText()) & squares[2].getText().equals(squares[8].getText()) ) {  
    								 theWinner = squares[2].getText();         
    								 highlightWinner(2,5,8);  
    							 }
    								 // Check the first diagonal  - array elements 0,4,8      
    								 if (!squares[0].getText().equals("") & squares[0].getText().equals(squares[4].getText()) & squares[0].getText().equals(squares[8].getText()) ) {  
    									 theWinner = squares[0].getText();        
    									 highlightWinner(0,4,8);   
    								 }
    									 // Check the second diagonal - array elements 2,4,6     
    									 if (!squares[2].getText().equals("") & squares[2].getText().equals(squares[4].getText()) & squares[2].getText().equals(squares[6].getText()) ) {  
    										 theWinner = squares[2].getText();          
    										 highlightWinner(2,4,6); 
    									 }
    									return theWinner;
    								}	 									 
    	/**  
    	 * This method applies a set of rules to find   
    	 * the best computer's move. If a good move   
    	 * can't be found, it picks a random square.   
    	 */  
     
    	void computerMove() {     
    		int selectedSquare; 
    		// Computer first tries to find an empty  
    		// square next the two squares with "O" to win      
    		selectedSquare = findEmptySquare("O");      
     
    		// if can't find two "O", at least try to stop the      
    		// opponent from making 3 in a row by placing      
    		// "O" next to 2 "X".     
    		if ( selectedSquare == -1 )         
    			selectedSquare =  findEmptySquare("X");              
     
    		// if the selectedSquare is still -1, at least       
    		// try to occupy the central square        
    		if ( (selectedSquare == -1)&&(squares[4].getText().equals("")) )        
    			selectedSquare=4;          
     
    		// no luck with the central either...     
    		// just get a random square     
    		if ( selectedSquare == -1 )        
    			selectedSquare = getRandomSquare();      
    			squares[selectedSquare].setText("O");     
    			squares[selectedSquare].setEnabled(false); 
    		}   
    	/**  
    	 * This method checks every row, column and diagonal  
    	 * to see if there are two squares with the same label  
    	 * and an empty square.   
    	 * @param   give X - for the user, and O for the computer   
    	 * @return  the number of the empty square to use,  
    	 *          or the negative 1 could not find 2 square  
    	 *          with the same label      
    	 */ 
    	int findEmptySquare(String player) {        
    		int weight[] = new int[9];     
    		for ( int i = 0; i < 9; i++ ) {         
    			if ( squares[i].getText().equals("O") )             
    				weight[i] = -1;         
    			else if ( squares[i].getText().equals("X") )             
    				weight[i] = 1;         
    			else             
    				weight[i] = 0;    
    			}     
     
    		int twoWeights = player.equals("O") ? -2 : 2;      
     
    		// See if row 1 has the same 2 squares and a blank     
    		if ( weight[0] + weight[1] + weight[2] == twoWeights ) {         
    			if ( weight[0] == 0 )             
    				return 0;         
    			else if ( weight[1] == 0 )             
    				return 1;         
    			else             
    				return 2;     
    			}    
     
    		// See if row 2 has the same 2 squares and a blank     
    		if ( weight[3] +weight[4] + weight[5] == twoWeights ) {         
    			if ( weight[3] == 0 )             
    				return 3;         
    			else if ( weight[4] == 0 )             
    				return 4;         
    			else             
    				return 5;     
    			}    
     
    		// See if row 3 has the same 2 squares and a blank     
    		if ( weight[6] + weight[7] +weight[8] == twoWeights ) {         
    			if ( weight[6] == 0 )             
    				return 6;         
    			else if ( weight[7] == 0 )             
    				return 7;         
    			else             
    				return 8;     
    			}    
     
    		// See if column 1 has the same 2 squares and a blank     
    		if ( weight[0] + weight[3] + weight[6] == twoWeights ) {         
    			if ( weight[0] == 0 )             
    				return 0;         
    			else if ( weight[3] == 0 )             
    				return 3; 
    			else             
    				return 6;     
    			}    
     
    		// See if column 2 has the same 2 squares and a blank     
    		if ( weight[1] +weight[4] + weight[7] == twoWeights ) {         
    			if ( weight[1] == 0 )             
    				return 1;         
    			else if ( weight[4] == 0 )             
    				return 4;         
    			else             
    				return 7;     
    			}    
     
    		// See if column 3 has the same 2 squares and a blank     
    		if ( weight[2] + weight[5] + weight[8] == twoWeights ) {         
    			if ( weight[2] == 0 )             
    				return 2;         
    			else if ( weight[5] == 0 )             
    				return 5;         
    			else             
    			return 8;     
    			}    
     
    		// See if diagonal 1 has the same 2 squares and a blank     
    		if ( weight[0] + weight[4] + weight[8] == twoWeights ) {         
    			if ( weight[0] == 0 )             
    				return 0;         
    			else if ( weight[4] == 0 )             
    				return 4;         
    			else             
    				return 8;     
    			}   	 
     
    		// See if diagonal has the same 2 squares and a blank     
    		if ( weight[2] + weight[4] + weight[6] == twoWeights ) {         
    			if ( weight[2] == 0 )             
    				return 2;         
    			else if ( weight[4] == 0 )             
    				return 4;         
    			else             
    				return 6;     
    			}     
     
    		// do not have the same two neighbors       
    		return -1;  } 
    	// end of findEmptySquare  
     
    	/**  
    	 * This method selects any empty square    
    	 * @return a randomly selected square number  
    	 */  
    	int getRandomSquare() {     
    		boolean gotEmptySquare = false;     
    		int selectedSquare = -1;      
    		do {    selectedSquare = (int) (Math.random() * 9 );      
    		if (squares[selectedSquare].getText().equals("")) {     
    			gotEmptySquare = true; // the looping will end        
    			}     
    		} while (!gotEmptySquare );      
    		return selectedSquare; 
    	} 
    	// end getRandomSquare()    
     
    	/**    
    	 * This method highlights the winning line   
    	 * @param first square to highlight   
    	 * @param second square to highlight   
    	 * @param third square to highlight  
    	 */   
     
    	void highlightWinner(int win1, int win2, int win3) {      
    		squares[win1].setBackground(Color.CYAN);  
    		squares[win2].setBackground(Color.CYAN);
    		squares[win3].setBackground(Color.CYAN); 
    		} 
     
    		/**  
    		 * Disables squares and enable New Game button  
    		*/  
    	void endTheGame(){   
    		for(int i=0;i<9;i++){    
    			squares[i].setEnabled(false);  
    			}  
     
    		// Enable the new game button 
    		newGameButton.setEnabled(true);      
    		} 
    	}


  2. #2
    Junior Member
    Join Date
    Aug 2012
    Location
    Germany
    Posts
    19
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Replacing an If statement with a Switch statement

    Have you thought about what your "win-calculation" algorithm would look like if the game has 200 fields (4 wins would be ugly in your way ? I would suggest to implement a recursive search algorithm to find full rows.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,619
    Thanks
    45
    Thanked 1,958 Times in 1,932 Posts

    Default Re: Replacing an If statement with a Switch statement

    Another approach would be to load an array with all the winning combinations and use it to search for winners.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Aug 2012
    Location
    Germany
    Posts
    19
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Replacing an If statement with a Switch statement

    But the bigger the gameboard the bigger the array

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,619
    Thanks
    45
    Thanked 1,958 Times in 1,932 Posts

    Default Re: Replacing an If statement with a Switch statement

    The array would contain the indexes of the winning positions. For the rows:
    int[][] winPos = new int[][] {{0,1,2}, {3,4,5}, etc}
    Then use those indexes to get to the board's contents:
    theBoard[winPos[r][c]] etc

    I used that idea in a Javascript program I wrote a while back:
    http://normsstuff.zxq.net/Games/TicTacToe.html
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    logi (February 2nd, 2013)

  7. #6
    Junior Member
    Join Date
    Jan 2013
    Location
    UK
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Replacing an If statement with a Switch statement

    Thanks for the replies guys.
    I did post earlier but it has not appeared on the forum so I will post again.


    noctarius I am not too sure how to implement a recursive search algorithm and I am not sure what you mean by " (4 wins would be ugly in your way?" You also say "the bigger the gameboard the bigger the array".
    But the game board only ever contains 9 squares. 3 squares across and 3 squares down.

    I will add a screenshot of the applet so you can have a better idea of the end result.


    And Norm, I understand what you are saying and i think that would be quite a good idea to use an array to store the possible wins.
    I will see if I can implement it properly.

    Thanks for the help guys.


    Heres the screenshot


  8. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Replacing an If statement with a Switch statement

    Moderator action: posts with images have been "approved" and should now be visible.

  9. The Following User Says Thank You to curmudgeon For This Useful Post:

    Norm (February 2nd, 2013)

  10. #8
    Junior Member
    Join Date
    Aug 2012
    Location
    Germany
    Posts
    19
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Replacing an If statement with a Switch statement

    i meant the game "4 wins" which has a lot bigger gameboard than tictactoe and then imagine your switch or if-block :-)

    Here's an older recursive winner search algorithm for an "4 wins" game I made (sorry for missing comments, I had to decompile the class file - no idea where the source is gone). The size of the gameboard is definable so in theory you could use it for tictactoe as well :-):
    public class GameBoard
    {
        public static int FIELD_TYPE_X = 1;
     
        public static int FIELD_TYPE_O = 2;
     
        public static int FIELD_TYPE_CLEAR = 0;
     
        private int gameboard[][];
     
        public static class Point
        {
     
            public int getX()
            {
                return x;
            }
     
            public int getY()
            {
                return y;
            }
     
            private final int x;
     
            private final int y;
     
            public Point( int x, int y )
            {
                this.x = x;
                this.y = y;
            }
        }
     
        public GameBoard( int columns, int rows )
        {
            gameboard = new int[6][6];
            gameboard = new int[columns][rows];
            clearBoard();
        }
     
        public Point[] put( int x, int type )
        {
            if ( x < 0 || x > gameboard.length )
                throw new IllegalArgumentException( "X is out of range" );
            int data[] = gameboard[x];
            for ( int y = 0; y < gameboard[0].length; y++ )
            {
                if ( data[y] != FIELD_TYPE_CLEAR )
                {
                    if ( y - 1 < 0 )
                        throw new IllegalArgumentException( "Y went out of range" );
                    setField( x, y - 1, type );
                    break;
                }
                if ( y != gameboard[0].length - 1 )
                    continue;
                setField( x, y, type );
                break;
            }
     
            return checkBoard( type );
        }
     
        public void setField( int x, int y, int type )
        {
            if ( gameboard[x][y] != FIELD_TYPE_CLEAR )
            {
                throw new IllegalArgumentException( "Field already set" );
            }
            else
            {
                System.out.println( ( new StringBuilder( "X: " ) ).append( x ).append( ", Y:" ).append( y ).append( ", TYPE: " ).append( type ).toString() );
                gameboard[x][y] = type;
                return;
            }
        }
     
        public void clearBoard()
        {
            for ( int x = 0; x < gameboard.length; x++ )
            {
                for ( int y = 0; y < gameboard[0].length; y++ )
                    gameboard[x][y] = FIELD_TYPE_CLEAR;
     
            }
     
        }
     
        public int[] getNextField( int x, int y, int direction )
        {
            int next[] = new int[2];
            if ( direction == 1 || direction == 4 || direction == 6 )
                next[0] = x - 1;
            else if ( direction == 2 || direction == 7 )
                next[0] = x;
            else if ( direction == 3 || direction == 5 || direction == 8 )
                next[0] = x + 1;
            if ( direction == 1 || direction == 2 || direction == 3 )
                next[1] = y - 1;
            else if ( direction == 4 || direction == 5 )
                next[1] = y;
            else if ( direction == 6 || direction == 7 || direction == 8 )
                next[1] = y + 1;
            return next;
        }
     
        public Point[] checkBoard( int type )
        {
            for ( int x = 0; x < gameboard.length; x++ )
            {
                for ( int y = gameboard[0].length; y > -1; y-- )
                {
                    for ( int direction = 1; direction < 9; direction++ )
                    {
                        Point points[] = new Point[4];
                        if ( checkField( x, y, type, 0, direction, points ) )
                            return points;
                    }
     
                }
     
            }
     
            return null;
        }
     
        private boolean checkField( int x, int y, int type, int count, int direction, Point points[] )
        {
            if ( x < 0 || x == gameboard.length || y < 0 || y == gameboard[0].length )
                return false;
            if ( gameboard[x][y] != type )
                return false;
            int newPosition[] = getNextField( x, y, direction );
            boolean value = checkField( newPosition[0], newPosition[1], type, count + 1, direction, points );
            if ( !value && count >= 3 || value )
            {
                if ( count <= 3 )
                    points[count] = new Point( x, y );
                return true;
            }
            else
            {
                return false;
            }
        }
     
        public static void main( String args[] )
        {
            GameBoard gameBoard = new GameBoard( 6, 6 );
            gameBoard.setField( 0, 0, FIELD_TYPE_X );
            gameBoard.setField( 1, 0, FIELD_TYPE_X );
            gameBoard.setField( 2, 0, FIELD_TYPE_X );
            gameBoard.setField( 3, 0, FIELD_TYPE_O );
            gameBoard.setField( 4, 0, FIELD_TYPE_O );
            gameBoard.setField( 5, 0, FIELD_TYPE_O );
            gameBoard.setField( 3, 1, FIELD_TYPE_X );
            gameBoard.setField( 4, 1, FIELD_TYPE_O );
            gameBoard.setField( 5, 1, FIELD_TYPE_X );
            gameBoard.setField( 4, 2, FIELD_TYPE_X );
            gameBoard.setField( 5, 2, FIELD_TYPE_O );
            gameBoard.setField( 1, 3, FIELD_TYPE_O );
            gameBoard.setField( 2, 3, FIELD_TYPE_X );
            gameBoard.setField( 3, 3, FIELD_TYPE_X );
            gameBoard.setField( 4, 3, FIELD_TYPE_X );
            gameBoard.setField( 5, 3, FIELD_TYPE_O );
            gameBoard.setField( 2, 4, FIELD_TYPE_X );
            gameBoard.setField( 3, 4, FIELD_TYPE_O );
            gameBoard.setField( 4, 4, FIELD_TYPE_O );
            gameBoard.setField( 5, 4, FIELD_TYPE_O );
            gameBoard.setField( 1, 5, FIELD_TYPE_X );
            gameBoard.setField( 2, 5, FIELD_TYPE_X );
            gameBoard.setField( 3, 5, FIELD_TYPE_O );
            gameBoard.setField( 4, 5, FIELD_TYPE_O );
            gameBoard.setField( 5, 5, FIELD_TYPE_X );
            Point points[] = gameBoard.checkBoard( FIELD_TYPE_X );
            if ( points == null )
            {
                System.out.println( "No winner found" );
            }
            else
            {
                System.out.println( "Winner found, stones are:" );
                for ( int i = 3; i > -1; i-- )
                    System.out.println( ( new StringBuilder( "X: " ) ).append( points[i].getX() ).append( " Y: " ).append( points[i].getY() ).toString() );
     
            }
        }
    }

  11. The Following User Says Thank You to noctarius For This Useful Post:

    logi (February 3rd, 2013)

  12. #9
    Junior Member
    Join Date
    Jan 2013
    Location
    UK
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Replacing an If statement with a Switch statement

    I understand you now mate. I had never herd of the game "4 wins" before.
    Thanks for the code, I will have a look at it and see if it is something that I would be able to implement.

  13. #10
    Junior Member
    Join Date
    Aug 2012
    Location
    Germany
    Posts
    19
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Replacing an If statement with a Switch statement

    Ah I see they called it "connect four" in english :-) Connect Four - Wikipedia, the free encyclopedia

Similar Threads

  1. [SOLVED] (beginner) Switch Statement
    By georgewbw in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 11th, 2011, 11:18 PM
  2. switch statement
    By Tank314 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 9th, 2011, 01:23 PM
  3. How do I loop a switch Statement?
    By Arkeshen in forum Java Theory & Questions
    Replies: 7
    Last Post: July 19th, 2011, 06:25 AM
  4. help with switch statement
    By robertsbd in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 12th, 2010, 12:52 PM
  5. [SOLVED] Switch statement question
    By shikh_albelad in forum Loops & Control Statements
    Replies: 5
    Last Post: May 31st, 2009, 05:13 AM