Heshamy Heshamy - 3 months ago 9
Java Question

Arraylist.indexOf() case sensitive

Okay, I have made a phonebook that does the follows,


  1. Add new contact

  2. Edit contact's phone

  3. Delete contact

  4. Search by name

  5. Search by phone

  6. View all contact

  7. Restore factory settings

  8. Exit



I've finished it and it's working properly, except one thing. If a name is stored for example "John" and the user searches for "john", it will print "not found", because j is not capitalized, how can I fix this without screwing up really bad with my code.

Here's the code for case 2 for example.

case 2: {
System.out.println("Enter the contact name you want to edit");
temp=s.next();
int z=name.indexOf(temp);
if(z!=-1)
{
System.out.println("Edit to?");
temp=s.next();
name.set(z, temp);
System.out.println("Name edited to "+temp);
}
else
System.out.println("Name not found");
break;
}

Answer

If you want all names to start with a capital letter you can only store them in this way, and then print in this way. The following code will help:

private String capitalize(String name) {
    String s1 = name.substring(0, 1).toUpperCase();
    String nameCapitalized = s1 + name.substring(1).toLowerCase();
    return nameCapitalized;
}

Use this method befor storing anything to your array and then ask for first occurence of capitalize(name);

In your case:

case 2: {
    System.out.println("Enter the contact name you want to edit");
    temp=s.next();
    int z=name.indexOf(capitalize(temp));
    if(z!=-1)
    {
        System.out.println("Edit to?");
        temp=s.next();
        name.set(z, capitalize(temp));
        System.out.println("Name edited to "+capitalize(temp));
    }
    else
        System.out.println("Name not found");
    break;
}

This approach will let you keep all names in the same convention - names starting with a capital letter.