I am trying to make a program that can add a customer's name, age, contact number and email. And I want to search for the name that the user wants, but it does not search the name even if I entered the same name exactly. How can I fix this?
Here is my code:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<customers> customers = new ArrayList<>();
customers.add(new customers("Zen",19,"0912121212","zen@gmail.com"));
customers.add(new customers("Mary",20,"09134343434","mary@gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println(customers.contains(name));
}
}
class customers{
private String name;
private int age;
private String contactNumber;
private String email;
public customers(String name, int age, String contactNumber, String email) {
this.name = name;
this.age = age;
this.contactNumber = contactNumber;
this.email = email;
}
}
List.contains()
uses Object.equals()
to determine whether an Object is already in that List.
So one approach could be to overwrite that method:
public class Customer
{
private String m_Name;
private int m_Age;
…
@Override
public final boolean equals( final Object o )
{
return o instanceof String name && name.equals( m_Name );
}
}
Although this will work, it is not recommended to implement equals()
in this way (see here as a starting point).
Instead you should search for the name in the list:
String name = scan.nextLine();
System.out.println( customers.stream().anyMatch( c -> c.getName().equals( name ) ) );
A completely different approach would be to store the Customer
objects not in an instance of List
but in an instance of Map
, with the name as the key:
public class Main
{
public static void main( String... args )
{
Scanner scan = new Scanner(System.in);
Map<String,Customer> customers = new HashMap<>();
var customer = new Customer( "Zen", 19, "0912121212", "zen@gmail.com" );
customers.put( customer.getName(), customer );
customer = new Customer( "Mary", 20, "09134343434", "mary@gmail.com" );
customers.put( customer.getName(), customer );
System.out.println( "Enter name: " );
String name = scan.nextLine();
System.out.println( customers.containsKey( name ) );
}
}
Finally, it would help in general if you would follow the basic naming conventions for the Java language: class names are starting with a Capital letter.