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

后端 未结 4 1086
执念已碎
执念已碎 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:26

    You should Override equals inside your Person class

    public boolean equals(Object obj) {
        if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
            return true;
        }
        return false;
    }
    

    Then just call:

    if(!(person1.equals(person2))) {
    //not a duplicate
    }
    

    And of course substitute the variables/objects with whatever objects you want. You also should add getters and setters for last and first name. Hope this helps!

提交回复
热议问题