【问题标题】:Counting occurrences in a string array and deleting the repeats using java计算字符串数组中的出现次数并使用java删除重复项
【发布时间】:2014-04-20 22:17:09
【问题描述】:

我遇到了代码问题。我已将文本文件中的单词读入字符串数组,删除了句点和逗号。现在我需要检查每个单词的出现次数。我也设法做到了。但是,我的输出包含文件中的所有单词以及出现的次数。 像这样: 2 鸟 2 是 1 去 2 北 2 北2

这是我的代码:

public static String counter(String[] wordList)
{
    //String[] noRepeatString = null ;
    //int[] countArr = null ;

    for (int i = 0; i < wordList.length; i++) 
    {
         int count = 1;
         for(int j = 0; j < wordList.length; j++)
         {
             if(i != j)  //to avoid comparing itself
             {
                 if (wordList[i].compareTo(wordList[j]) == 0)   
                 {
                     count++;
                     //noRepeatString[i] = wordList[i];
                     //countArr[i] = count;
                 }
             }
         }

         System.out.println (wordList[i] + " " + count);

     }

    return null; 

我需要弄清楚 1) 将计数值放入数组中。2) 删除重复。 正如评论中所见,我尝试使用 countArr[] 和 noRepeatString[],希望这样做.. 但我有一个 NullPointerException。

对此问题的任何想法将不胜感激:)

【问题讨论】:

  • 有什么理由不使用集合(ListSet 等)?
  • 你能告诉我们你有什么厌倦导致 NullPointerException
  • 还是个初学者..我最终会学会的。
  • @sansix 你是什么意思?如果我删除那些评论标记,它会导致 NullPointerException。
  • 你应该从掌握集合开始之前掌握数组恕我直言;与集合相比,数组是一种“痛苦”(无法调整大小、需要操作索引等)

标签: java arrays string counter


【解决方案1】:

我会先将数组转换为列表,因为它们比数组更容易操作。

List<String> list = Arrays.asList(wordsList);

然后您应该创建该列表的副本(稍后您将了解原因):

ArrayList<String> listTwo = new ArrayList<String>(list);

现在您删除第二个列表中的所有重复项:

HashSet hs = new HashSet();
hs.addAll(listTwo);
listTwo.clear();
listTwo.addAll(hs);

然后你遍历第二个列表并获取该单词在第一个列表中的频率。但首先你应该创建另一个 arrayList 来存储结果:

ArrayList<String> results = new ArrayList<String>;
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": " count;
results.add(result);
}

终于可以输出结果列表了:

for(String freq : results){
System.out.println(freq);}

我还没有测试过这段代码(现在不能这样做)。请询问是否有问题或不起作用。请参阅以下问题以供参考:

How do I remove repeated elements from ArrayList?

One-liner to count number of occurrences of String in a String[] in Java?

How do I clone a generic List in Java?

【讨论】:

  • 有没有办法不用list或hash?
  • 您可能可以以某种方式做到这一点,但这更优雅。看看列表和散列,了解新东西总是好的,因为人们需要它来解决问题。以此为契机,学习这两件事!你会经常使用它们。 :) 如果您发现此答案有用,请将其标记为已接受:D
  • 将来我会 :) 但是我的讲师将此范围设置为基本内容。无论如何感谢您的努力。真的很感激
【解决方案2】:

您的代码中存在一些语法问题,但工作正常

ArrayList<String> results = new ArrayList<String>();
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": "+ count;
results.add(result);
}

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 2021-03-21
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多