Java address book. How to prevent duplicate contacts in my code?

后端 未结 4 1081
执念已碎
执念已碎 2021-01-29 01:59
switch(menuChoice) {

case 1: 
    System.out.println(\"Enter your contact\'s first name:\\n\");
    String fname = scnr.next();
    System.out.println(\"Enter your cont         


        
4条回答
  •  礼貌的吻别
    2021-01-29 02:35

    Here is the code for keeping out duplicate ID's.

    public void addContact(Person p) {
    
        for(int i = 0;  i < ArrayOfContacts.size(); i++) {
            Person contact = ArrayOfContacts.get(i);
            if(contact.getID() == p.getID()) {
                System.out.println("Sorry this contact already exists.");
                return; // the id exists, so we exit the method. 
            }
        }
    
        // Otherwise... you've checked all the elements, and have not found a duplicate
        ArrayOfContacts.add(p);
    
    }
    

    If you would like to change this code to keep out duplicate names, then do something like this

    public void addContact(Person p) {
        String pName = p.getFname() + p.getLname();
        for(int i = 0;  i < ArrayOfContacts.size(); i++) {
            Person contact = ArrayOfContacts.get(i);
            String contactName =  contact.getFname() + contact.getLname(); 
            if(contactName.equals(pName)) {
                System.out.println("Sorry this contact already exists.");
                return; // the name exists, so we exit the method. 
            }
        }
    
        // Otherwise... you've checked all the elements, and have not found a duplicate
        ArrayOfContacts.add(p);
    
    }
    

提交回复
热议问题