Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException 5

0

I have a problem in a recursion project, the error it shows is "Exception in thread" main "java.lang.ArrayIndexOutOfBoundsException" The project is a TaTeTi or TicTacToe game in which moves are entered with coordinates and then the winner is announced.

If someone can help me solve it is an urgent project, I copy the code:

package laboratorio;

import java.util.Scanner;


public class Laboratorio {
    static Scanner entrada = new Scanner(System.in);

    /**
     * @param args the command line arguments
     */
        static  int c = 0;
        static int f = 0;
    public static void main(String[] args) {

            menu(); 


    }

    public static void menu()
    {
        char matriz [][] = new char[3][3];
        char jugador = 'X';  


        System.out.println("");  
        System.out.println("0 - Salir"); 
        System.out.println("1 - Comenzar juego"); 
        System.out.println("Elija un punto del menu anterior");
        int menu = entrada.nextInt();

        if (menu == 1)
        {    
            llenarMatriz(matriz, 0, 0);
            imprimirMatriz(matriz,0,0);
            System.out.println();
            gestionarTurnos(matriz, jugador);

        }
        else if (menu == 0) {
            System.exit(menu);            
        }
        else {
            System.out.println(); 
            System.out.println("Debe ingresar una opcion de menu correcta");
            menu(); 
        }

    }



    public static void llenarMatriz (char [][] matriz, int f, int c)
    {       
        matriz[f][c] = '-';
        if(c != matriz[0].length -1 || f!=matriz.length -1) //Estoy en la ultima columna 
        {
            if(c == matriz[0].length - 1)
            {               
                f++; //Paso a la siguiente fila
                c = 0; //Comienza de la primer columna

            }
            else {
                c++;                  
            }
            llenarMatriz(matriz, f, c);  
        }


    }

    public static void imprimirMatriz (char matriz [][], int f, int c)
    {       
        System.out.print(matriz[f][c] + ""); //muestro el primer elemento

        if(c != matriz[0].length -1 || f!=matriz.length -1) //Estoy en la ultima columna 
        {
            if(c == matriz[0].length - 1)
            {
                f++; //Paso a la siguiente fila
                c = 0; //Comienza de la primer columna
                System.out.println(); 
            }
            else {
                c++; 
            }
            imprimirMatriz(matriz, f, c);  
        }

    }


   public static boolean comprobarCasilla (char [][] matriz, int fila, int columna)
    {
        String guionaux = "-";
        char guion = guionaux.charAt(0);
        boolean esta = false;
        if (matriz[fila][columna] == guion && fila<=matriz.length -1 && columna <= matriz[0].length-1)
        {
        esta = true;
        }
        return esta;    
    }

    public static void pedirJugada (char [][] matriz, char jugador)
    {     

        System.out.print("Jugador "+jugador+" ingrese la fila de su jugada: ");
        int fila = entrada.nextInt(); 
        System.out.print("Jugador "+jugador+" ingrese la columna de su jugada: ");
        int columna = entrada.nextInt();
        if (comprobarCasilla(matriz, fila,columna) == true)
        {            
            matriz[fila][columna] = jugador; 
            imprimirMatriz(matriz, 0, 0);

        }
        else {       
            System.out.print("El casillero esta ocupado, ingrese las coordenadas nuevamente");
            System.out.println();
            pedirJugada(matriz, jugador); 
            }

    }    



    public static void gestionarTurnos (char [][] matriz, char jugador)
    {
//        int f=0;
//        int c=0; 
        if (buscarGanador (matriz, f, c)==1)
            {
                        //gestionarTurnos(matriz, jugador);
                pedirJugada(matriz, jugador); 

                    if (jugador=='X')
                    {               
                        jugador='O';
                        gestionarTurnos(matriz, jugador);
                    }
                    else
                    {
                        jugador='X';
                        gestionarTurnos (matriz, jugador);
                    }            
            }
        else if (buscarGanador (matriz, f, c)==2)
            {
            System.out.println("Oh!Parece que tenemos un empate!");
            menu();
            }
        else{
            System.out.println("Felicidades"+jugador+". Ganaste!!!");
            }



    }


public static boolean jugadaGanadoraHorizontal (char [][] matriz, int f, int c)
{

   boolean ganaste= false;
        if (matriz[f][c]==matriz[f][c+1]&&matriz[f][c]==matriz[f][c+2] && matriz[f][c+1]!='-')
        {
            ganaste=true;          

        }
        else if(f < matriz.length-1) {

            ganaste = jugadaGanadoraHorizontal(matriz, f+1, c); 
        }
   return ganaste;
}

public static boolean jugadaGanadoraVertical (char [][] matriz, int f, int c)
{
    boolean ganaste= false;
    if (c<=2)
    {
        if (matriz[f][c]==matriz[f + 1][c]&&matriz[f][c]==matriz[f+2][c] && matriz[f][c]!='-')
        {
            ganaste=true;
            System.out.print((matriz[0][c])+ "ha ganado vertical");
        }
        else 
        {
            if(c< matriz.length)
            {
               // ganaste = jugadaGanadoraVertical(matriz, f, c); 
            }

        }
    }
    return ganaste;
}


public static boolean jugadaGanadoraDiagonal (char [][] matriz, int f, int c)
    {
        boolean ganador = false; 
        if (matriz[f][c+2]==matriz[f+1][c+1] && matriz[f][c+2]==matriz[f+2][c] && matriz[f][c+2]!='-') //diagonal derecha
            {
                ganador = true; 
                System.out.print( "ha ganado diagonal");
            }

        return ganador; 
    }

public static int hayEmpate (char matriz [][], int f, int c, int ocurrencia)
    {      
        System.out.print(matriz[f][c] + ""); //muestro el primer elemento

        if(c != matriz[0].length -1 || f!=matriz.length -1) //Estoy en la ultima columna 
        {
            if(c == matriz[0].length - 1)
            {
                f++; //Paso a la siguiente fila
                c = 0; //Comienza de la primer columna
                 if (matriz[f][c]=='-')
                 {
                 ocurrencia++;
                 }
            }
            else {
                   c++; 
                        if (matriz[f][c]=='-')
                         {
                         ocurrencia++;
                         }
                    hayEmpate(matriz, f, c, ocurrencia); 
                }
        }
             return ocurrencia;  

    }


public static int buscarGanador (char matriz [][], int f, int c) 
{
int resultado=0;
if (jugadaGanadoraHorizontal(matriz,f,c)==false)
{
    if (jugadaGanadoraVertical(matriz,f,c)==false)
    {
     if (jugadaGanadoraDiagonal (matriz, f, c)==false)
     {
        if (hayEmpate(matriz, f, c,0)!= 0 )
            {
            resultado=1;//no hay empate, ni jugada ganadora
            }
        else 
           {
           resultado=2;//hay empate
           }
     }
     else
     {
     resultado=3;//ganador diagonal
     }
    }
    else
    {
    resultado=3;//ganador vertical
    }
}
else
{
if (jugadaGanadoraVertical(matriz,f,c)==false)
    {
     if (jugadaGanadoraDiagonal (matriz, f, c)==false)
     {
        if (hayEmpate(matriz, f, c,0)!= 0 )
            {
            resultado=3;
            }
        else 
           {
           resultado=3;
           }
     }
     else
     {
     resultado=3;
     }
    }//Siempre retorna 3 porque ya la horizontal de por si es true
}
return resultado;
}
}
    
asked by Jesica Franco 14.07.2018 в 00:09
source

1 answer

0

ArrayIndexOutOfBoundsException means you're trying to access a fix, but you're getting out of bounds.

In your case it is caused because you are not checking if what the player is within the limits of the game board. The program only accepts coordinates between zero and two for X and Y . But the player is free to enter a number greater than two, that's where the error ArrayIndexOutOfBoundsException is generated. You can fix it like this:

public static void pedirJugada (char [][] matriz, char jugador)
{     

    System.out.print("Jugador "+jugador+" ingrese la fila de su jugada: ");
    int fila = entrada.nextInt(); 
    System.out.print("Jugador "+jugador+" ingrese la columna de su jugada: ");
    int columna = entrada.nextInt();
    if (fila >= 3 || columna >=3) { // Revisar si está dentro de los límites
        System.out.println("Las coordenadas no son correctas");
        System.out.println("Intentelo otra vez");
        pedirJugada(matriz, jugador);
    }
    else if (comprobarCasilla(matriz, fila,columna) == true) // 'else if' para evitar el error.
    {            
        matriz[fila][columna] = jugador; 
        imprimirMatriz(matriz, 0, 0);

    }
    else {       
        System.out.print("El casillero esta ocupado, ingrese las coordenadas nuevamente");
        System.out.println();
        pedirJugada(matriz, jugador); 
        }

}

PS: Even with this repair, the user is free to enter letters or any other symbol, which will generate a InputMismatchExeption if it is not a number. I'll leave you with homework how to avoid that.

    
answered by 14.07.2018 в 12:36