Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Arraylist.contains returning false

I’m doing an exercise in which I have to create a phonebook, but I have a question about one of the options I need to do in the menu, which I have to search the user’s contact by name, but when I loop through the ArrayList with user input, the program returns "false", even though the name is in the list.

Output

===MENU===
1. Register New Contact
2. Search all contacts
3. Search contact by name
Your choice: 2

Here's the only contact on your agenda...
Jon, 99999-9999, jon@gmail.com, 01/01/2000

===MENU===
1. Register New Contact
2. Search all contacts
3. Search contact by name
4. Delete contact
5. Exit
Your choice: 3
Enter the name of the contact you want to search:
Jon
false 
//Here it's returning false, in addition to what I wanted it to return true, 
// I'd also like to know how to print the list that got true in the .contains method

Contato.class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Contato {
  // Atributos da classe Contato
  private int id;
  private String nome;
  private String telefone;
  private String email;  
  private String aniversario;
  
  public int getID() {
    return id;
  }
  public void setID(int id) {
    this.id = id;
  }
  
  public String getNome() {
    return nome;
  }
  public void setNome(String nome) {
    this.nome = nome;
  }
  
  public String getTelefone() {
    return telefone;
  }
  public void setTelefone(String telefone) {
    this.telefone = telefone;
  }
  
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }

  public String getAniversario() {
    return aniversario;
  }
  public void setAniversario(String aniversario) {
    this.aniversario = aniversario;
  }
  
  public Contato(String nome, String telefone) {
    this.id = id;
    this.nome = nome;
    this.telefone = telefone;
    this.email = "Email not entered";
    this.aniversario = "Birthday date not entered";
  }
  
   @Override
   public String toString() {
     return nome + ", " + telefone + ", " + email + ", " + aniversario;
  }
}

Main.class

import java.util.Scanner;
import java.util.ArrayList;
import java.util.StringJoiner;
 
public class Main {
  public static void main(String args[]){
    Scanner entrada = new Scanner(System.in);
    int id;
    String nome, telefone, email, aniversario;
    ArrayList<Contato> contatos = new ArrayList<>();
     
    while(true){
      System.out.println("\n===MENU===");
      System.out.println("1. Register New Contact");
      System.out.println("2. Search all contacts");
      System.out.println("3. Search contact by name");
      System.out.print("Your choice: ");
      int opcao = Integer.parseInt(entrada.nextLine());
       
      switch(opcao) {
        case 1:
          System.out.print("Nome: ");
          nome = entrada.nextLine();
          System.out.print("Telefone: ");
          telefone = entrada.nextLine();
          Contato novoContato = new Contato(nome, telefone);
          System.out.print("E-mail: ");
          email = entrada.nextLine();
          novoContato.setEmail(email);
          System.out.print("Aniversário: ");
          aniversario = entrada.nextLine();
          novoContato.setAniversario(aniversario);

          contatos.add(novoContato);
          System.out.print("\nO contato foi adicionado na sua agenda!\n");
          break;
        case 2:
          int quantContatos= contatos.size();
          if (quantContatos == 0) {
            System.out.println("\nVocê ainda não adicionou contatos na agenda!");
          } else if (quantContatos == 1) {
            System.out.print("\nAqui está o único contato da sua agenda...\n");
            StringJoiner todosContatos = new StringJoiner("\n");
            for (Contato contato : contatos) {
            todosContatos.add(contato.toString());
          }
            System.out.println(todosContatos);
          } else {
            System.out.print("\nAqui estão os " + quantContatos + " contatos da sua agenda...\n");
            StringJoiner todosContatos = new StringJoiner("\n");
            for (Contato contato : contatos) {
            todosContatos.add(contato.toString());
          }
            System.out.println(todosContatos); 
          }
          break;
        case 3:
          System.out.println("Insira o nome do contato que deseja buscar: ");       
          nome = entrada.nextLine();
          for (Contato contato : contatos) {
              System.out.println(contatos.contains(nome));
          }
          break;
    }
  }
}

The problem is in case 3 of the switch, if someone could help me solve it, I would appreciate it

>Solution :

What you need is to check the contato nome property, not the contato object itself. With contatos.contains(nome) you are checking if a list of Contato contains a String, which will always be false. What you need is the following:

case 3:
    System.out.println("Insira o nome do contato que deseja buscar: ");
    nome = entrada.nextLine();
    String finalNome = nome;
    List<Contato> contatosComNome = contatos.stream().filter(contato -> contato.getNome().equals(finalNome))
            .collect(Collectors.toList());
    System.out.println(contatosComNome);
    break;

You need to basically filter the contatos list to only keep the ones with nome equal to the nome entered by the user. Your final code would look like below:

public class Main {
    public static void main(String args[]) {
        Scanner entrada = new Scanner(System.in);
        int id;
        String nome, telefone, email, aniversario;
        ArrayList<Contato> contatos = new ArrayList<>();

        while (true) {
            System.out.println("\n===MENU===");
            System.out.println("1. Register New Contact");
            System.out.println("2. Search all contacts");
            System.out.println("3. Search contact by name");
            System.out.print("Your choice: ");
            int opcao = Integer.parseInt(entrada.nextLine());

            switch (opcao) {
                case 1:
                    System.out.print("Nome: ");
                    nome = entrada.nextLine();
                    System.out.print("Telefone: ");
                    telefone = entrada.nextLine();
                    Contato novoContato = new Contato(nome, telefone);
                    System.out.print("E-mail: ");
                    email = entrada.nextLine();
                    novoContato.setEmail(email);
                    System.out.print("Aniversário: ");
                    aniversario = entrada.nextLine();
                    novoContato.setAniversario(aniversario);

                    contatos.add(novoContato);
                    System.out.print("\nO contato foi adicionado na sua agenda!\n");
                    break;
                case 2:
                    int quantContatos = contatos.size();
                    if (quantContatos == 0) {
                        System.out.println("\nVocê ainda não adicionou contatos na agenda!");
                    } else if (quantContatos == 1) {
                        System.out.print("\nAqui está o único contato da sua agenda...\n");
                        StringJoiner todosContatos = new StringJoiner("\n");
                        for (Contato contato : contatos) {
                            todosContatos.add(contato.toString());
                        }
                        System.out.println(todosContatos);
                    } else {
                        System.out.print("\nAqui estão os " + quantContatos + " contatos da sua agenda...\n");
                        StringJoiner todosContatos = new StringJoiner("\n");
                        for (Contato contato : contatos) {
                            todosContatos.add(contato.toString());
                        }
                        System.out.println(todosContatos);
                    }
                    break;
                case 3:
                    System.out.println("Insira o nome do contato que deseja buscar: ");
                    nome = entrada.nextLine();
                    String finalNome = nome;
                    List<Contato> contatosComNome = contatos.stream().filter(contato -> contato.getNome().equals(finalNome))
                            .collect(Collectors.toList());
                    System.out.println(contatosComNome);
                    break;
            }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading