简体   繁体   中英

Compare elements within an array

I am creating a project where the user enters names of multiple sports teams. The user is not allowed to enter the same name of a team twice. I can't figure out how to compare elements of an array. I tried to use a while loop with equals but I don't think it's the right way.

for(int i = 0; i<tabEquipe.length;i++){ // tabEquipe is the table content of the teams that the user enters.
        System.out.println("Entrez les noms des equipes: "); // Asks user to enter team names.
        rep2 = a.nextLine();
       tabEquipe[i] = rep2;
       while(tabEquipe[i].equals(tabEquipe[i])){

       }
    }

That's confusing, so I assume you have already a new user you want to add, and it seems you can compare users with equals . If there's a new user newUser then it could look like this:

boolean found = false;
for(int i = 0; i < tabEquipe.length; i++){ 
   if (tabEquipe[i].equals(newUser))
   {
      found = true;
      break; 
   }
}

or, shorter:

boolean found = Arrays.asList(tabEquipe).contains(newUser);

You can use a HashSet to store the names of teams in such a manner that the check if a new name was already used happens very efficiently. For example:

...

Set<String> teamNamesSet = new HashSet<>();

for (int i = 0; i < teamNames.length; i++) {
 ...

 // Checking if a team name was already used
 while (teamNamesSet.contains(name)) {
  // Show some error message, request input again, etc.
 }

 // Adding a new team name to the set
 teamNamesSet.add(name);

 // Adding a new team name also to the array you need
 teamNames[i] = name;
}

The great advantage of this approach is that the check if a name is already in a HashSet takes a constant time ( O(1) ). Using a for loop to check has a linear complexity ( O(n) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM