Home > Software engineering >  Tictactoe crashes of value is greater or equal to 9
Tictactoe crashes of value is greater or equal to 9

Time:12-03

Editing my sister's tic-tac-toe code and she (also I) hit a snag. If Player one was to type a number greater than 9 or type a number that at was already used it will crash. Is there and recommended solution to problem.

printGameBoard(gameBoard);

        //User input requests
        while(true) {
            System.out.println("Enter your placement (1-9):");
            int playerPos = scan.nextInt();
            while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPositions) || cpuPositions.contains(playerPos)){
                System.out.println("Position taken! Enter another position:");
                playerPos = scan.nextInt();
                //Prevent user from printing on top of CPU
                while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPos)){
                    System.out.println("Position taken! Enter another position:");
                    playerPos= scan.nextInt();
                }
            }

            placePiece(gameBoard, playerPos, "player");

            String result = checkWinner();
            if(result.length() > 0) {
                System.out.println(result);
                break;            
            }
            //CPU random positions (this what you are looking for)
            Random rand = new Random();
            int cpuPos = rand.nextInt(9)   1;
            while(playerPositions.contains(cpuPos) || cpuPositions.contains(cpuPos)){
                cpuPos = rand.nextInt(9)   1;
            }

            placePiece(gameBoard, cpuPos, "cpu");

            printGameBoard(gameBoard);

            result = checkWinner();
            if(result.length() > 0){
                System.out.println(result);
                break;
            }
        }

    }

    public static void placePiece(char[][] gameBoard, int pos, String user){

        char symbol = ' ';

        if(user.equals("player")){
            symbol = 'X';
            playerPositions.add(pos);
        } else if(user.equals("cpu")){
            symbol = 'O';
            cpuPositions.add(pos);
        }

        switch(pos){
            case 1:
                gameBoard[0][0] = symbol;
                break;
            case 2:
                gameBoard[0][2] = symbol;
                break;
            case 3:
                gameBoard[0][4] = symbol;
                break;
            case 4:
                gameBoard[2][0] = symbol;
                break;
            case 5:
                gameBoard[2][2] = symbol;
                break;
            case 6:
                gameBoard[2][4] = symbol;
                break;
            case 7:
                gameBoard[4][0] = symbol;
                break;
            case 8:
                gameBoard[4][2] = symbol;
                break;
            case 9:
                gameBoard[4][4] = symbol;
                break;                          
            default:
                break;
        }
    }

    public static String checkWinner(){        
        // (This define what a winng move looks like) 
        List topRow = Arrays.asList(1, 2, 3);
        List midRow = Arrays.asList(4, 5, 6);
        List botRow = Arrays.asList(7, 8, 9);
        List leftCol = Arrays.asList(1, 4, 7);
        List midCol = Arrays.asList(2, 5, 8);
        List rightCol = Arrays.asList(3, 6, 9);
        List cross1 = Arrays.asList(1, 5, 9);
        List cross2 = Arrays.asList(7, 5, 3);

        List<List> winning = new ArrayList<List>();
        winning.add(topRow);
        winning.add(midRow);
        winning.add(botRow);
        winning.add(leftCol);
        winning.add(midCol);
        winning.add(rightCol);
        winning.add(cross1);
        winning.add(cross2);

        for(List l : winning){
            if(playerPositions.containsAll(l)){
                return "Congraduations you won!";
            } else if(cpuPositions.containsAll(l)){
                return "CPU wins! Sorry!";
            } else if(playerPositions.size()   cpuPositions.size() == 9){
                return "We are tied!";
            }
        }

        return "";       
    }

    public static void printGameBoard (char [][] gameBoard){ 
        for(char[] row : gameBoard) {
            for(char c : row) {
                System.out.print(c);              
            }
            System.out.println();
        }
    }
}


PLAYGAME CODE

import java.util.*;

public class PlayGame
{
    private int incrementer;
    private char location[]=new char[10];
    private char gamer;

    public static void main(String args[])
    {
        String ch;
        PlayGame Toe=new PlayGame();
        do{
            Toe.beginBoard();
            Toe.startplay();
            System.out.println ("Would you like to play again (Enter 'Y')? ");
            Scanner in =new Scanner(System.in);
            ch=in.nextLine();
            System.out.println("ch value is " ch);
        }while (ch.equals("Y"));

    }
    public void beginBoard()
    {

        char locationdef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'};
        int i;
        incrementer = 0;
        gamer = 'X';
        for (i=1; i<10; i  ) location[i]=locationdef[i];
        presentBoard();

    }
    public String presentBoard()
    {
        System.out.println( "\n\n" );
        System.out.println( "\n\n" );
        System.out.println( "\n\n\t\t"   location [1]   " | "  location [2]  " | "  location [3]);
        System.out.println( " \t\t | | " );
        System.out.println( " \t\t ___|____|___ " );
        System.out.println( "\n\n\t\t"  location [4]  " | "  location [5]  " | "  location [6]);
        System.out.println( " \t\t | | " );
        System.out.println( " \t\t ___|____|___ " );
        System.out.println( "\n\n\t\t"  location [7]  " | "  location [8]  " | "  location [9]);
        System.out.println( " \t\t | | " );
        System.out.println( " \t\t | | " );
        System.out.println( "\n\n" );
        return "presentBoard";
    }

    public void startplay()
    {
        int center;
        char blank = ' ';

        System.out.println( "gamer "   locategamer()  " will go first and be the letter 'X'" );

        do {
            presentBoard();

            System.out.println( "\n\n gamer "   locategamer()  " choose a location." );

            boolean currentlocation = true;
            while (currentlocation) {

                Scanner in =new Scanner (System.in);
                center=in.nextInt();
                currentlocation = checklocation(center);
                if(currentlocation==false)
                    location[center]=locategamer();
            }

            System.out.println( "Excellent move" );

            presentBoard();

            latergamer();
        }while ( getWinner() == blank );

    }

    public char getWinner()
    {
        char Winner = ' ';

        if (location[1] == 'X' && location[2] == 'X' && location[3] == 'X') Winner = 'X';
        if (location[4] == 'X' && location[5] == 'X' && location[6] == 'X') Winner = 'X';
        if (location[7] == 'X' && location[8] == 'X' && location[9] == 'X') Winner = 'X';
        if (location[1] == 'X' && location[4] == 'X' && location[7] == 'X') Winner = 'X';
        if (location[2] == 'X' && location[5] == 'X' && location[8] == 'X') Winner = 'X';
        if (location[3] == 'X' && location[6] == 'X' && location[9] == 'X') Winner = 'X';
        if (location[1] == 'X' && location[5] == 'X' && location[9] == 'X') Winner = 'X';
        if (location[3] == 'X' && location[5] == 'X' && location[7] == 'X') Winner = 'X';
        if (Winner == 'X' )
        {System.out.println("gamer1 wins the game." );
            return Winner;
        }

        if (location[1] == 'O' && location[2] == 'O' && location[3] == 'O') Winner = 'O';
        if (location[4] == 'O' && location[5] == 'O' && location[6] == 'O') Winner = 'O';
        if (location[7] == 'O' && location[8] == 'O' && location[9] == 'O') Winner = 'O';
        if (location[1] == 'O' && location[4] == 'O' && location[7] == 'O') Winner = 'O';
        if (location[2] == 'O' && location[5] == 'O' && location[8] == 'O') Winner = 'O';
        if (location[3] == 'O' && location[6] == 'O' && location[9] == 'O') Winner = 'O';
        if (location[1] == 'O' && location[5] == 'O' && location[9] == 'O') Winner = 'O';
        if (location[3] == 'O' && location[5] == 'O' && location[7] == 'O') Winner = 'O';
        if (Winner == 'O' )
        {
            System.out.println( "gamer2 wins the game." );
            return Winner; }

        for(int i=1;i<10;i  )
        {
            if(location[i]=='X' || location[i]=='O')
            {
                if(i==9)
                {
                    char Draw='D';
                    System.out.println(" Game is draw ");
                    return Draw;
                }
                continue;
            }
            else
                break;

        }

        return Winner;
    }

    public boolean checklocation(int center)
    {

        if (location[center] == 'X' || location[center] == 'O')
        {
            System.out.println("That location is already occupied please choose another location");
            return true;
        }
        else {
            return false;
        }


    }


    public void latergamer()
    {
        if (gamer == 'X')
            gamer = 'O';
        else gamer = 'X';

    }

    public String locatename()
    {
        return " Game Tic Tac Toe" ;
    }

    public char locategamer()
    {
        return gamer;
    }

}

i found code to fix redundant input, but not the crash when input is higher than 9

CodePudding user response:

The recommended way is to check the input first and reject it if it is an invalid location (less than 1 or greater than 9).

In the class PlayGame that would mean to change the checklocation() method:

    public boolean checklocation(int center)
    {
        if (center < 1 || 9 < center)
        {
            System.out.println("That location is not valid please choose another location");
            return true;
        }
        else if (location[center] == 'X' || location[center] == 'O')
        {
            System.out.println("That location is already occupied please choose another location");
            return true;
        }
        else {
            return false;
        }
    }

CodePudding user response:

A possible solution to this issue would be to add additional checks to the input to make sure that the number entered is between 1 and 9 and has not already been used. For example, you could add an if statement that checks if the entered number is valid, and if not, prompts the user to enter a new number until a valid one is provided. You could also add a list of used numbers (similar to the playerPositions and cpuPositions lists) and check if the entered number is in that list before allowing the user to place their piece on the game board.

  •  Tags:  
  • java
  • Related