Error comparing the name of two contacts in an arraylist agenda_telefono

1

I am programming a phone book using arrayList. I want to compare the names and print that the contact can not be added to the calendar if they are repeated. I miss this error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at recursos.agenda_telefonica.aniadirContacto(agenda_telefonica.java:15)
    at principal.principal.main(principal.java:20).

I leave the code:

public class Contacto {

    private String nombre;
    private int numero;

    public Contacto(String nombre, int numero) {
        this.nombre = nombre;
        this.numero = numero;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public int getNumero() {
        return numero;
    }

    public void setNumero(int numero) {
        this.numero = numero;
    }


}

Class agenda_telefonica:

package recursos;

import java.util.ArrayList;
import java.util.Iterator;

public class agenda_telefonica {

    private final static int TAMANIO = 10;   
    ArrayList <Contacto> listatel = new ArrayList <Contacto>();
    Contacto contacto;

    public void aniadirContacto(Contacto c){ 
            listatel = new ArrayList();
            for (int i = 0; i < 10; i++) {
                if(c.getNombre().equals(listatel.get(i).getNombre())){
                    System.out.println("No se puede agregar");
                }else{
                    listatel.add(c);
                }

        }
    }        
    public void existeContacto(Contacto c){
        if(listatel.contains(c)){
            System.out.println("Este contacto ya existe");
        }else{
            System.out.println("Este contacto no existe");
        }             
    }
    public void buscaContacto(String nombre){
        for (int i = 0; i < listatel.size(); i++) {
            if(nombre.equals(listatel.get(i).getNombre())){
                System.out.println(listatel.get(i).getNumero());
            }
        }
    }
    public void eliminarContacto(Contacto c){
        listatel.remove(c);

        if(!listatel.contains(c)){
            System.out.println("Se ha eliminado correctamente");
        }else{
            System.out.println("No se ha eliminado");
        }
    }
    public void agendaLlena(){
        if(listatel.size()>=10){
            System.out.println("Agenda llena");
        }else{
            System.out.println("Lugar disponible");
        }
    }
    public void huecosLibres(){
        int hueco_libre = agenda_telefonica.TAMANIO - listatel.size();
        System.out.println(hueco_libre);
    }
}


    public static void main(String[] args) {
        // TODO code application logic here
        Contacto c01 = new Contacto("carlos", 1555750721);
        Contacto c02 = new Contacto("pablo", 1555750811);
        Contacto c03 = new Contacto("ezequiel", 1567820721);
        Contacto c04 = new Contacto("nati", 1553340721);
        Contacto c05 = new Contacto("carlos", 1555712421);

        agenda_telefonica agenda = new agenda_telefonica();

        agenda.aniadirContacto(c01);
        agenda.aniadirContacto(c02);
        agenda.aniadirContacto(c03);
        agenda.aniadirContacto(c04);
aca deberia darme el mensaje "No se puede agregar"
        agenda.aniadirContacto(c05);

        agenda.buscaContacto("pablo");
        System.out.println(c01.getNombre());
    }

}
    
asked by carpopper 17.12.2018 в 17:16
source

2 answers

1

There is a problem in the life cycle of your application. You can not start the listatel = new ArrayList(); list of contacts each time you add a contact as this will delete the ones you have already added in that list. You are already initializing the list when you declare it:

ArrayList <Contacto> listatel = new ArrayList <Contacto>();

What makes it unnecessary to re-instantiate it in another method. the error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 means that when you try to compare your list in the for, it does not have anything in position i so it means that your list is EMPTY and my solution is as follows:

Boolean var = true;
 for (int i = 0; i < listatel.size(); i++) {
            if(c.getNombre().equals(listatel.get(i).getNombre())){
                var = false
            }
    }

if(var){
  listatel.add(c);
}else{
  System.out.println("No se puede agregar");
 }

You must tell the for that the number of times you are going to repeat is the same number of contacts that you have on your list, since this will make if your list is empty, never enter the for. And you must add the contact outside the for because if you leave the method ready.add inside the for, it will add this contact as many times as the for is iterated, that is, you can add it once to the list as you can add it 10.

    
answered by 17.12.2018 / 17:51
source
1

You have this method:

public void aniadirContacto(Contacto c){ 
    listatel = new ArrayList();                   //Creas un ArrayList vacío SIEMPRE
    for (int i = 0; i < 10; i++) {                // asumes que tiene 10 elementos
        if(c.getNombre().equals(listatel.get(i).getNombre())){
            System.out.println("No se puede agregar");
        }else{
             listatel.add(c);
        }

    }
}

Since that ArrayList is empty, there is not even position 0. When trying to access that position, you have that IndexOutOfBoundsException (translated means Exception: Index out of range ).

The correct way to implement it would be

public void aniadirContacto(Contacto c){ 
    if (listatel ==null) {
        listatel = new ArrayList();  //Creas un ArrayList vacío si no hay uno
    }
    for (int i = 0; i < listatel.size(); i++) {                
        if(c.getNombre().equals(listatel.get(i).getNombre())){
            System.out.println("No se puede agregar");
        }else{
             listatel.add(c);
        }

    }
}
    
answered by 17.12.2018 в 17:41