0

This error appears everytime and it's a problem.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at frasesencadenadas.FrasesEncadenadas.main(FrasesEncadenadas.java:34) BUILD FAILED (total time: 4 seconds)

Any help?

Code:

package frasesencadenadas;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class FrasesEncadenadas {

public static void main(String[] args) {

    System.out.println("JUEGO EXTENDIDO DE PALABRAS ENCADENADAS");
    System.out.println("---------------------------------------");
    String f1;
    String p1,p2;
    String r1,r2;
    boolean victoria;
    int n=1, f=1;
    int score1=0, score2=0;
    int con = 0, x=0;
    Scanner entrada = new Scanner(System.in);
        System.out.println("Introducir el nombre del primer jugador: ");
        p1 = entrada.nextLine();
        System.out.println("Introducir el nombre del segundo jugador: ");
        p2 = entrada.nextLine();
        System.out.println("¡Comienza el juego!");
        System.out.println("Partida " + n + ":Puntos " + p1 + ": " + score1 + ", Puntos " + p2 + ": " + score2);
        System.out.println("Frase " + f + " de " + p1 + ":");
        f1=entrada.nextLine();
    ArrayList<String> frases;
    frases = new ArrayList<String>(Arrays.asList(f1.split(" ")));
    do {
    con = 0;
    String palabra0 = frases.get(x);
    String palabrafin = frases.get((frases.size() - 1 -x));
    for(int i = 0; i < palabra0.length(); i++) {
        for (int j = 0; j < palabrafin.length(); j++) {
                if (palabra0.charAt(i) == palabrafin.charAt(j)) {
                con++;  
                }
        }
    }
    x++;

    }while ((x <= ((frases.size()-1))) || (con >= 3));
    System.out.println(con);
    if (con >= 3) {
                victoria = true;
            } else {
                victoria = false;
            }
    System.out.println(victoria);
    System.out.println("Respuesta de: " + p2);
    r2 = entrada.nextLine();
    r2.toLowerCase();
}

}

Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
  • 1
    You're trying to access the third element in a list with only 2. Have you debugged to find out why that is? – Carcigenicate May 07 '17 at 18:44
  • I think you've got an integer overflow going on, with `x`. I suspect that the `||` on line 44 should be `&&` instead. Think carefully about whether you really mean "or" or "and". – Dawood ibn Kareem May 07 '17 at 19:21

0 Answers0