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

huangapple go评论60阅读模式
英文:

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

问题

我写了一个用于查找数组中一个名字重复了多少次的代码有一些问题

我需要这个问题在没有任何集合框架映射集合或数组的情况下解决只通过循环来解决

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; //设置计数器
		for(j=i+1;j<len-1;j++)
		{
			if(b[i].equals(b[j]))
			{
				c++;
				for(t=j;t<len-1;t++)
				{

//通过将重复的元素替换为下一个元素来删除重复的元素
b[t]=b[t+1];
}
}
}
System.out.println(b[i]+" 重复了 "+ c +" 次 ");
len-=c-1; //减少循环次数,减去元素重复的次数
}
}

}


输入:

    HAROLD
    HAROLD
    HAROLD
    JAVA
    JOKER
    HOLD
    JAVA
    KOI
    JAVA
    GOAT
    
输出:

    HAROLD 重复了 2 次 
    HAROLD 重复了 1 次 
    JAVA 重复了 3 次 
    JOKER 重复了 1 次 
    HOLD 重复了 1 次 
    KOI 重复了 1 次 
    GOAT 重复了 1 次 
英文:

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.

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&lt;10;i++)
		{
			a[i]=sc.nextLine();
			b[i]=a[i];
		}
		int len=b.length;
		for(i=0;i&lt;len;i++)
		{
			c=1; //Setting Counter
			for(j=i+1;j&lt;len-1;j++)
			{
				if(b[i].equals(b[j]))
				{
					c++;
					for(t=j;t&lt;len-1;t++)
					{
//Deleting the repeated element by replacing with the next element
						b[t]=b[t+1];
					}
			    }
		 	}
			 System.out.println(b[i]+&quot; is repeated &quot;+ c +&quot; times &quot;);
			 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 

答案1

得分: 1

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

其次,请为您的变量始终提供有意义的名称,尤其是如果您打算从其他人那里获得帮助。我们无法知道一个名为 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;
         /* 而不是使用第二个数组,我们可以简单地使用一个嵌套的 for 循环,其中索引从 1 开始。
         您将始终将当前元素与下一个元素进行比较。
         */
         for(int j = 1;j< a.length;j++)
         {
           if(a[i].equals(a[j]))
           {
            count++;
           }
         }
         System.out.println(a[i]+" is repeated "+ count +" times ");
       }
   }
}

请注意,这将重复打印结果,也就是说,输入 HAROLD * 3 将导致输出为 "COUNT FOR HAROLD IS 3" 连续打印三次。

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

对于这种问题,这并不是数组的理想用法。如果没有实际原因阻止您使用集合,那么您绝对应该使用 HashMap 来解决这种类型的问题,以避免重复打印值。

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

至于为什么您的代码失败了:
在您的 T 循环中,您重新分配了 B 数组中的项目,使其成为下一个元素。

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

英文:

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. i and j are OK to indicate index, but for anything else, use significant names.

Lastly, it is a bad practice to declare iterators outside of for loops. Always try to declare and initialize your iterator variables inside the for loop. This will avoid many headaches when your code is large and you won't lose track of something like 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 &lt; a.length; i++)
      {
           System.out.println(&quot;Enter word: &quot;);
           a[i]=sc.nextLine();
      }
            
      for(int i=0;i&lt; 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&#39;ll always be comparing the current element with the         
         next one.
         */
         for(int j = 1;j&lt; a.length;j++)
         {
           if(a[i].equals(a[j]))
           {
            count++;
           }
         }
         System.out.println(a[i]+&quot; is repeated &quot;+ count +&quot; times &quot;);
       }
   }
  

}

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
&quot;COUNT FOR HAROLD IS 3&quot; printed three times.

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.

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.

As a possible workaround, you may try adding another for loop at the beginning, to count the unique words you have in your array. 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.
Lastly, iterate through this uniqueWords array to print its elements.

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.

So, it worked twice for Harold because B[t] was Harold, and B[t+1] was Harold as well.
But for the third iteration, B[t] is Harold and B[t+1] is Java.
Therefore, only one instance of Harold was found and the previous Harolds had been overwritten by the reassignment.

答案2

得分: 0

代替循环,您可以像下面这样使用 Map:

// 假设您有包含姓名的数组 "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);
}

// 打印频率
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
    System.out.println(entry.getKey() + " 重复了 " + entry.getValue() + " 次。");
}
英文:

Instead of looping, you can use Map like below


//Assuming you have array &quot;names&quot; containing names
String[] names = new String[10];
Map&lt;String,Integer&gt; countMap = new HashMap&lt;String,Integer&gt;();
for(int i=0;i&lt;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&lt;String,Integer&gt; entry : countMap.entrySet()) {
	 
	 System.out.println(entry.getKey()+&quot; is repeated &quot;+entry.getValue()+ &quot; times.&quot;);
}

答案3

得分: 0

你可以使用一个单一的数组和一个哈希映射来找出项目重复的次数。
在下面的解决方案中,我循环遍历字符串数组 'a' 一次,并用字符串值填充一个哈希映射,然后要么通过递增来计算值,要么将其赋值为1。
然后,我可以循环遍历哈希映射的键集(所有字符串值),然后打印出它们的值,这将是它们重复的次数。

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 + " 重复了 " + mapOfNames.get(s) + " 次。");
}

将会打印:

JAVA 重复了 3 次。
JOKER 重复了 1 次。
KOI 重复了 1 次。
HAROLD 重复了 3 次。
GOAT 重复了 1 次。
HOLD 重复了 1 次。
英文:

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.

Map&lt;String, Integer&gt; mapOfNames = new HashMap&lt;&gt;();
        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 + &quot; is repeated &quot; + mapOfNames.get(s) + &quot; times.&quot;);
        }

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.

答案4

得分: 0

import java.util.*;

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

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&lt;10; i++ ) {
            System.out.print(&quot;&gt;&gt;&gt;&quot;);
            a[i]=sc.nextLine();
            b[i]=false;
        }

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

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

If you need the number of times the name appeared in the list the use

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

Or if you want the number of time the name is repeated, then use

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

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

huangapple
  • 本文由 发表于 2020年9月11日 13:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63841376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定