Java arralist does not return data

Asked

Viewed 203 times

1

My doubt consists in the following problem.

I am building an application (didactic purposes). It has a Contact class that receives a String with name, a String with the phone, and the constructor initializes the date and time of the object creation. A Schedule class that handles the instance contacts like adding in an Arraylist contacts, as long as the name is not there or the phone.

I have a method that takes a String and should return all occurrences that start String within the collection. Example:

have the objects: joão silva, Joãozinho, joãozão - the method receives joão. In this case the method would return all occurrences with joão.

Well thought, I walk through the Arraylist checking if the name field matches the word and add to a local Array and return it. I use the startsWith() method to check. However, it is not returning anything though, contacts have been added. I couldn’t find anything that would help me. Someone could clear up by giving us new points of view to improve my thinking?

Below the code of the agenda class that receives the contacts objects.

import java.util.*;
/**
 * Responsável por armazenar os contatos.
 * 
 * @author (Vinicius Cavalcanti) 
 * @version (26.05.2016)
 */

public class Schedule
{
// Campos.
private ArrayList<Contact> contacts;

/**
 * Construtor:
 * Recebe instancia um lista de contatos.
 * @param contact: recebe um objeto do tipo Contact.
 */
public Schedule()
{
    contacts = new ArrayList<Contact>();
}

/**
 * Método que insere um contato na agenda.
 * @param contact: instancia um objeto Contact.
 * impede que outro contato com o mesmo nome seja inserido ou;
 * se o telefone está vinculado a outro contato.
 */
public void insertContact(Contact contactNew)
{
    //Para o caso da lista estiver vazia.
    if (contacts.isEmpty())
      contacts.add(contactNew);

    else
    {
        String phoneNew;
        String nameNew;

        phoneNew = contactNew.getPhone();
        nameNew = contactNew.getName();

        //Condição para adicionar o contato
        if(searchPhone(phoneNew) == null && searchName(nameNew) == false)
            contacts.add(contactNew);
        else
        {
            //caso o telefone já exista.
            if(searchPhone(phoneNew) != null)
                System.out.println("telefone " + phoneNew + " está vinculado a outro contato");

            //caso o nome já exista.
            if (searchName(nameNew) == true)
                System.out.println("Contato " + nameNew + " já existe");
        }
    }
}

/**
 * Método que faz uma busca dos contatos adicionados.
 * @param name: é o parâmetro da busca.
 */
public ArrayList<Contact> searchEarly(String name)
{
    ArrayList<Contact> search;
    search = new ArrayList<Contact>();

    Iterator<Contact> it = contacts.iterator();

    while(it.hasNext())
    {
        Contact contact = it.next();

        if(contact.getName().startsWith(name))
            search.add(contact);
    }

    return search;
}

/**
 * Método que faz uma busca nos contatos adicionados baseado no telefone.
 * retornar para qual o telefone está vinculado.
 * @param phone: telefone a qual deseja consultar.
 */
public Contact searchPhone(String phone)
{
    for (int index = 0; index < contacts.size(); index++)
    {
        if (contacts.get(index).getPhone().equals(phone))
          return contacts.get(index);
    }

    return null;
}

public void imprime()
{
    System.out.println("------------------------------");
    if (contacts.isEmpty())
      System.out.println("Não existe contatos a serem exibidos");
    else
      for (int i = 0; i < contacts.size(); i++)
        System.out.println("Nome: " + contacts.get(i).getName() + " Telefone: " + contacts.get(i).getPhone() 
                                    + " criando em: " + contacts.get(i).getDate());
}

/**
 * método que retonar se o nome já existe na ArrayList contacts ou não
 */
private boolean searchName(String searchName)
{
    for (int index = 0; index < contacts.size(); index++)
    {
        if ( contacts.get(index).getName().equals(searchName) )
          return true;
    }
    return false;
}
}

Contact class code:

import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * Instancia o objeto contato.
 * 
 * @author (Vinicius Cavalcanti) 
 * @version (26.05.2016)
 */
public class Contact
{
// Campos.
private String name;
private String phone;
private Date dateHour;
private SimpleDateFormat sdf;

/**
 * Construtor:
 * * @param name: instancia o atributo nome.
 * * @param phone: instancia o atritubo telefone.
 * Seta a data e hora que o objeto foi criado.
 */
public Contact(String name, String phone)
{
    setName(name);
    setPhone(phone);
    this.dateHour = new Date();
    this.sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
}

/**
 * Método setter que altera o nome.
 * @param name: recebe o nome com variável do tipo String.
 */
public void setName(String name)
{
    this.name = name;
}
/**
 * Método setter que altera o telefone.
 * @param phone: recebe o telefone com a variável do tipo String.
 */
public void setPhone(String phone)
{
    this.phone = phone;
}

/**
 * Método getter que retonar o nome instanciado.
 */
public String getName()
{
    return this.name;
}

/**
 * Método getter que retonar o telefone instanciado.
 */
public String getPhone()
{
    return this.phone;
}

/**
 * Método getter que retonar a data e hora da criação do objeto.
 * No tipo String com o formato dia/mês/ano 00:00:00
 */
public String getDate()
{
    return sdf.format(this.dateHour);
}

/**
 * Método exibe as informações do objeto.
 * Nome, telefone e data de criação.
 */
public void imprime()
{
    System.out.print("Nome: " + this.name + " \nTelefone: " + this.phone + " \nCraindo em: " + getDate());
}

public String toString()
{
    String text = "";

    return this.name + " - " + this.phone + " - " + getDate(); 
}
}

thanks in advance for the help!

1 answer

0


Try this code on your searchEarly method:

public ArrayList<Contact> searchEarly(String name)
{
    ArrayList<Contact> search;
    search = new ArrayList<Contact>();

    for(int i = 0; i < contacts.size(); i++)
    {
        Contact c = (Contact)contacts.get(i);

        if(c.getName().startsWith(name))
            search.add(contact);
    }

    return search;
}
  • asks the contact object of the method . add() was not instantiated who you are referring to the variable c?

  • Marcus compiled his code here without making any changes and it worked. You’re adding the objects Contacts in his method insertContact class Schedule? When you run the method print out appears the list of all contacts? Another point, the method searchEarly distinguishes capital letters from minuscules (Case Sensitive).

  • that the method insertContact() is responsible for adding contacts as long as it passes under conditions (name and phone different from the list). Yes the print method is normal, in the terminal it prints all the list right, no it does not differentiate (the passed string has to be equal to the stored contact)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.