我已经尝试使用下面的代码,虽然它可以工作,但不能满足requirement.Please分享您的知识,谢谢
String temp;
for(int i = 0; i < lexicon.size(); i++)
{
for (int j = lexicon.size() - 1; j > i; j--)
{
if (lexicon.get(i).compareTo(lexicon.get(j)) > 0)
{
temp = lexicon.get(i);
lexicon.set(i,lexicon.get(j)) ;
lexicon.set(j,temp);
}
}
}
ArrayList<String> uniqueWords = new ArrayList<String>();
for(int i = 0; i < lexicon.size(); i++) //Removing duplicates
{
int wordCount = 1;
uniqueWords.add(lexicon.get(i));
for(int j = i+1; j < lexicon.size(); j++)
{
if(uniqueWords.get(i).equals(lexicon.get(j)))
{
wordCount++;
lexicon.remove(j);
}
}
System.out.println(uniqueWords.get(i) + " " + wordCount);
}这是我得到的输出:
a 6
a 3
a 2
about 1
acknowledged 1
all 1
also 1
and 2
answer 1
at 2
austen 1
be 2
been 1
bennet 2
bennet 1我需要这样的东西:那个词的字数统计
a 11
about 1
acknowledge 1诸若此类
发布于 2019-04-24 17:00:01
问题是,你在lexicon.remove(j);上删除了你的词典中的元素,并在lexicon.get(j)上检查了你的词典
我不想给你完整的代码,因为你不会从中学到任何东西,但我希望我给了你足够的提示,来解决你的问题。尝试调试您的代码,看看变量发生了什么:)
发布于 2019-04-24 17:01:10
在索引j处删除时,j get的值增加了j++,实际上跳过了一个值,而这个值本应继续而不增加。
正如已经排序的:
String word = uniqueWords.get(i);
int j = i+1;
while (j < lexicon.size() && word.equals(lexicon.get(j)))
{
wordCount++;
lexicon.remove(j);
}(我将给出代码,因为它显示了一种稍微不同的方法。)
https://stackoverflow.com/questions/55825656
复制相似问题