Help with Program in JAVA: ArrayIndexOutOfBoundsException

1

I have a program that pretends to be a Contacts Diary, the problem is that adding more data to ArrayList the program does not work for me:

public ArrayList<modeloPersona> LeerTodoArchivo(String Archivo){
    ArrayList<modeloPersona> personaArreglo = new  ArrayList<modeloPersona>();
    modeloPersona persona; 

    try {
        File file = new File(Archivo);
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String linea;
        while ((linea = bufferedReader.readLine()) != null) {       
            String[] partes = linea.split(",");
            persona = new modeloPersona();//SE CONSTRUYE
            persona.setNombre(partes[0]);
            persona.setTelefono(partes[1]);
            persona.setDireccion(partes[2]);
            // persona.setEdad(partes[3]);
            // persona.setComentario(partes[4]);

            personaArreglo.add(persona);        
        }
        fileReader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return personaArreglo;
}

The problem is that when you add, for example, a:

persona.setEdad(partes[3]); and persona.setComentario(partes[4]);

It does not leave me, it only lets me have three positions from 0 to 2.

Show me the error

  

ArrayIndexOutOfBoundsException

    
asked by Henry 18.09.2018 в 16:47
source

1 answer

2

The problem is that the line content contains 3 items separated by ",", example:

 linea = "palabra0, palabra1, palabra2";
 String[] partes = linea.split(",");

therefore you can only get the elements:

partes[0] = "palabra0";
partes[1] = "palabra1";
partes[2] = "palabra2";

If the line content had 5 elements separated by ",",

 linea = "palabra0, palabra1, palabra2, palabra3, palabra4";
 String[] partes = linea.split(",");

then you could get the elements with index 3 and 4:

partes[0] = "palabra0";
partes[1] = "palabra1";
partes[2] = "palabra2";
partes[3] = "palabra3";
partes[4] = "palabra4";

You must ensure that the lines of the file you are trying to read have 5 items separated by ",".

You can also validate the case in which the elements of the array are not found , in this case the elements would not be added to the object:

   ...
   ...
    while ((linea = bufferedReader.readLine()) != null) {
        String[] partes = linea.split(",");
        persona = new modeloPersona();//SE CONSTRUYE

        if(partes.length >0) {
            persona.setNombre(partes[0]);
        }
        if (partes.length >1){
            persona.setTelefono(partes[1]);
        }
        if (partes.length >2){
           persona.setDireccion(partes[2]);
        }
        if (partes.length >3){
           persona.setEdad(partes[3]);
        }
        if (partes.length >4) {
            persona.setComentario(partes[4]);
        }

        personaArreglo.add(persona);

    }
  ...
  ...
    
answered by 18.09.2018 в 17:13