简体   繁体   English

比较数组中的元素

[英]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.我尝试使用带等号的 while 循环,但我认为这不是正确的方法。

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 .这很令人困惑,所以我假设您已经有一个要添加的新用户,并且您似乎可以将 users 与equals进行比较。 If there's a new user newUser then it could look like this:如果有一个新用户newUser那么它可能看起来像这样:

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.您可以使用HashSet来存储团队的名称,这样可以非常有效地检查是否已经使用了新名称。 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) ).这种方法的最大优点是检查一个名称是否已经在HashSet中需要一个恒定的时间( O(1) )。 Using a for loop to check has a linear complexity ( O(n) ).使用 for 循环进行检查具有线性复杂度 ( O(n) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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