简体   繁体   English

如何查找名称在列表中重复的次数?

[英]How do I find number of times a name has been repeated in a list?

I wrote a code for finding how many times a name is repeated in an array, there is some issue with it.我写了一个代码来查找一个名字在数组中重复的次数,它有一些问题。

I need this to be done without any kind of collections framework (Maps, Set or Array) and only targeting to solve this by loops only.我需要在没有任何类型的集合框架(Maps、Set 或 Array)的情况下完成此操作,并且仅针对仅通过循环来解决此问题。

package string;
import java.util.*;
public class CountingNames {

    public static void main(String[] args) {
        int i,j,t,c;
        String a[]=new String[10];
        String b[]=new String[10];
        Scanner sc=new Scanner(System.in);
        for(i=0;i<10;i++)
        {
            a[i]=sc.nextLine();
            b[i]=a[i];
        }
        int len=b.length;
        for(i=0;i<len;i++)
        {
            c=1; //Setting Counter
            for(j=i+1;j<len-1;j++)
            {
                if(b[i].equals(b[j]))
                {
                    c++;
                    for(t=j;t<len-1;t++)
                    {
//Deleting the repeated element by replacing with the next element
                        b[t]=b[t+1];
                    }
                }
            }
             System.out.println(b[i]+" is repeated "+ c +" times ");
             len-=c-1; //Decreasing the loop by the number of times the element has been repeadted
       }
   }

}

INPUT:输入:

HAROLD
HAROLD
HAROLD
JAVA
JOKER
HOLD
JAVA
KOI
JAVA
GOAT

OUTPUT:输出:

HAROLD is repeated 2 times 
HAROLD is repeated 1 times 
JAVA is repeated 3 times 
JOKER is repeated 1 times 
HOLD is repeated 1 times 
KOI is repeated 1 times 
GOAT is repeated 1 times 

First of all, some general tips: Avoid declaring several variables in one line.首先,一些一般提示: 避免在一行中声明多个变量。 This doesn't help readability.这无助于可读性。

Secondly, please always provide significant names to your variables, especially if you intend to get help from other people.其次,请始终为您的变量提供重要的名称,特别是如果您打算从其他人那里获得帮助。 We cannot tell what a variable named p is supposed to do.我们无法判断名为p的变量应该做什么。 i and j are OK to indicate index, but for anything else, use significant names. i 和 j 可以表示索引,但对于其他任何事情,请使用有意义的名称。

Lastly, it is a bad practice to declare iterators outside of for loops.最后,在 for 循环之外声明迭代器是一种不好的做法。 Always try to declare and initialize your iterator variables inside the for loop.始终尝试在 for 循环中声明和初始化迭代器变量。 This will avoid many headaches when your code is large and you won't lose track of something like i .当您的代码很大并且您不会忘记像i这样的东西时,这将避免许多麻烦。

Now, your code could use some further refactoring.现在,您的代码可以使用一些进一步的重构。 A second array is totally unnecessary.第二个数组是完全没有必要的。

public class CountWords {
   public static void calculate(){
            
      String a[]=new String[10];
      Scanner sc=new Scanner(System.in);
      for(int i = 0; i < a.length; i++)
      {
           System.out.println("Enter word: ");
           a[i]=sc.nextLine();
      }
            
      for(int i=0;i< a.length; i++)
      {
         int count = 1;
         /*rather than having a 2nd array, we can simply 
         have a nested for loop where the index starts at 1.
         you'll always be comparing the current element with the         
         next one.
         */
         for(int j = 1;j< a.length;j++)
         {
           if(a[i].equals(a[j]))
           {
            count++;
           }
         }
         System.out.println(a[i]+" is repeated "+ count +" times ");
       }
   }
  

}

Keep in mind that this will print the results repeated, that is to say, an input of HAROLD * 3 will result in the output being "COUNT FOR HAROLD IS 3" printed three times.请记住,这将重复打印结果,也就是说,输入HAROLD * 3 将导致输出打印 3 次"COUNT FOR HAROLD IS 3"

If you wish to strictly count the amount of times a word is repeated , that is, we don't care about its first occurrence, then initialize count to 0 rather than 1.如果你想严格计算一个单词重复的次数,即我们不关心它的第一次出现,那么将count初始化为0而不是1。

This is not an ideal use for arrays.这不是数组的理想用途。 If there is no actual reason preventing you from using collections, you should absolutely use a HashMap for this type of problems to avoid the re-print of values.如果没有实际原因阻止您使用集合,则绝对应该对此类问题使用 HashMap 以避免重新打印值。

As a possible workaround, you may try adding another for loop at the beginning, to count the unique words you have in your array.作为一种可能的解决方法,您可以尝试在开头添加另一个 for 循环,以计算数组中的唯一单词。 Store the amount in an int variable, then, create a new array with the size of that variable, and instead of printing into the console, add the word count result to a string, then proceed to insert that string into the uniqueWords array, using similar logic to NOT insert the count message if its already present in the uniqueWords array.将数量存储在一个int变量中,然后创建一个具有该变量大小的新数组,而不是打印到控制台,而是将字数结果添加到一个字符串中,然后继续将该字符串插入到 uniqueWords 数组中,使用如果计数消息已存在于 uniqueWords 数组中,则不插入计数消息的类似逻辑。 Lastly, iterate through this uniqueWords array to print its elements.最后,遍历这个 uniqueWords 数组以打印其元素。

As to why your code failed: In your T for loop, You were reassigning the items in your B array to be the next element.至于为什么您的代码失败:在您的 T for 循环中,您将 B 数组中的项目重新分配为下一个元素。

So, it worked twice for Harold because B[t] was Harold, and B[t+1] was Harold as well.因此,它对 Harold 有效两次,因为 B[t] 是 Harold,而 B[t+1] 也是 Harold。 But for the third iteration, B[t] is Harold and B[t+1] is Java.但是对于第三次迭代,B[t] 是 Harold,B[t+1] 是 Java。 Therefore, only one instance of Harold was found and the previous Harolds had been overwritten by the reassignment.因此,只找到了一个 Harold 实例,并且之前的 Harold 已被重新分配覆盖。

Instead of looping, you can use Map like below您可以使用 Map 代替循环,如下所示


//Assuming you have array "names" containing names
String[] names = new String[10];
Map<String,Integer> countMap = new HashMap<String,Integer>();
for(int i=0;i<names.length;i++) {
     
     if(countMap.get(names[i]) != null)
         countMap.put(names[i],countMap.get(names[i])+1);
     else
         countMap.put(names[i],1);
 }
//Print your frequencies

for(Map.Entry<String,Integer> entry : countMap.entrySet()) {
     
     System.out.println(entry.getKey()+" is repeated "+entry.getValue()+ " times.");
}

You can use a single array and a hash map to find the number of times the items are repeated.您可以使用单个数组和哈希映射来查找项目重复的次数。 In the below solution, I loop over the String array 'a' once and populate a HashMap with the String value and then I either calculate the value by incrementing it, or I assign it the value of 1. I can then loop over the HashMap key set (all the string values) and then print out their values which will be ht number of times they are repeated.在下面的解决方案中,我循环遍历字符串数组 'a' 一次并使用字符串值填充 HashMap,然后我要么通过递增它来计算该值,要么将其赋值为 1。然后我可以遍历 HashMap键集(所有字符串值),然后打印出它们的值,这些值将是它们重复的次数。

Map<String, Integer> mapOfNames = new HashMap<>();
        for(String s: a){
            if(mapOfNames.containsKey(s)){
                mapOfNames.put(s, mapOfNames.get(s) + 1);
            }
            else{
                mapOfNames.put(s, 1);
            }
        }

        for(String s : mapOfNames.keySet()){
            System.out.println(s + " is repeated " + mapOfNames.get(s) + " times.");
        }

Will print:将打印:

JAVA is repeated 3 times.
JOKER is repeated 1 times.
KOI is repeated 1 times.
HAROLD is repeated 3 times.
GOAT is repeated 1 times.
HOLD is repeated 1 times.

public class App {
    public static void main(String[] args) {
        int i,j;
        String a[]=new String[10];
        boolean b[]=new boolean[10];
        Scanner sc=new Scanner(System.in);

        for(i=0; i<10; i++ ) {
            System.out.print(">>>");
            a[i]=sc.nextLine();
            b[i]=false;
        }

        for(i=0; i<10; i++ ) {
            int count = 0;

            if (!b[i]) {
                for(j=0 ; j<10 ; j++ ) {
                    if (a[i].equals(a[j])) {
                        count++;
                        b[j]=true;
                    }
                }
                System.out.println(a[i] + " is repeated " + (count-1) + " times" );
                // If you need the number of times the name appeared then use the below line
                // System.out.println(a[i] + " is repeated " + (count) + " times" );
            }
        }
   }
}

If you need the number of times the name appeared in the list the use如果您需要名称出现在列表中的次数,请使用

System.out.println(a[i] + " is repeated " + (count) + " times" );

Or if you want the number of time the name is repeated, then use或者,如果您想要名称重复的次数,请使用

System.out.println(a[i] + " is repeated " + (count-1) + " times" );

Input:-输入:-

HAROLD
HAROLD
HAROLD
JAVA
JOKER
HOLD
JAVA
KOI
JAVA
GOAT

Output:-输出:-

HAROLD is repeated 2 times
JAVA is repeated 2 times
JOKER is repeated 0 times
HOLD is repeated 0 times
KOI is repeated 0 times
GOAT is repeated 0 times

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

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