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

Java 如何查找一个名称在列表中重复的次数?,java,arrays,string,Java,Arrays,String,我编写了一个代码,用于查找一个名称在数组中重复了多少次,这是有问题的 我需要在没有任何类型的集合框架(映射、集合或数组)的情况下完成这项工作,并且仅通过循环来解决这一问题 package string; import java.util.*; public class CountingNames { public static void main(String[] args) { int i,j,t,c; String a[]=new String[10

我编写了一个代码,用于查找一个名称在数组中重复了多少次,这是有问题的

我需要在没有任何类型的集合框架(映射、集合或数组)的情况下完成这项工作,并且仅通过循环来解决这一问题

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
       }
   }

}
输出:

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 

您可以使用如下所示的映射,而不是循环


//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.");
}

//假设您有包含名称的数组“names”
字符串[]名称=新字符串[10];
Map countMap=新的HashMap();

对于(int i=0;i,您可以使用单个数组和哈希映射来查找项目的重复次数。 在下面的解决方案中,我在字符串数组“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.");
        }

首先,一些常规提示:避免在一行中声明多个变量。这无助于可读性

其次,请始终为变量提供重要名称,特别是如果您打算从其他人那里获得帮助。我们无法判断名为
p
的变量应该做什么。i和j可以表示索引,但对于其他任何内容,请使用重要名称

最后,在for循环外声明迭代器是一种不好的做法。请始终尝试在for循环内声明和初始化迭代器变量。这将避免在代码较大时遇到许多麻烦,并且不会丢失诸如
i
之类的内容

现在,您的代码可以进行进一步的重构。完全不需要第二个数组

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 ");
       }
   }
  

}
公共类CountWords{
公共静态无效计算(){
字符串a[]=新字符串[10];
扫描仪sc=新的扫描仪(System.in);
for(int i=0;i
请记住,这将打印重复的结果,即
HAROLD
*3将导致输出
“HAROLD的计数为3”
打印三次

如果您希望严格计算一个单词的重复次数,也就是说,我们不关心它的首次出现,然后将
count
初始化为0,而不是1

这不是数组的理想用途。如果没有实际原因阻止您使用集合,则绝对应该使用HashMap解决此类问题,以避免重新打印值

作为一种可能的解决方法,您可以尝试在开始时添加另一个for循环,以计算数组中的唯一单词。将数量存储在
int
变量中,然后使用该变量的大小创建一个新数组,而不是打印到控制台中,将单词计数结果添加到字符串中,然后继续d将该字符串插入uniqueWords数组,如果count消息已经存在于uniqueWords数组中,则使用类似的逻辑不插入该消息。 最后,遍历这个uniqueWords数组以打印其元素

关于代码失败的原因: 在T for循环中,将B数组中的项重新分配为下一个元素

因此,它对哈罗德起了两次作用,因为B[t]是哈罗德,B[t+1]也是哈罗德。 但是对于第三次迭代,B[t]是Harold,B[t+1]是Java。 因此,只找到了一个Harold实例,以前的Harold已被重新分配覆盖


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" );
            }
        }
   }
}
输出:-

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

只是一个提示:将输入与处理分开。您编写的代码要求每次您想要测试时……您必须手动输入名称。不要这样做。从硬编码数组开始,让您的代码使用该数组。只有当处理似乎有效时,才用手动输入替换硬编码数据。和:Java go Ca中的类名melCase,总是这样。所以像
CountingExample
那样调用你的类: 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" ); } } } }
HAROLD
HAROLD
HAROLD
JAVA
JOKER
HOLD
JAVA
KOI
JAVA
GOAT
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