【发布时间】: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。
对此问题的任何想法将不胜感激:)
【问题讨论】:
-
有什么理由不使用集合(
List、Set等)? -
你能告诉我们你有什么厌倦导致 NullPointerException
-
还是个初学者..我最终会学会的。
-
@sansix 你是什么意思?如果我删除那些评论标记,它会导致 NullPointerException。
-
你应该从掌握集合开始之前掌握数组恕我直言;与集合相比,数组是一种“痛苦”(无法调整大小、需要操作索引等)
标签: java arrays string counter