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

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

    Use a HashSet. For every user's name, add it to the HashSet.

    For example:

    HashSet namesUsed = new HashSet();
    
    if (namesUsed.contains(userName)) {
        //do what you want here, if this is entered it means there is a duplicate
    } else {
        namesUsed.add(userName); //add it to the list of used names
    }
    

提交回复
热议问题