【发布时间】:2015-12-24 05:39:50
【问题描述】:
由于我是 java 新手,我的任务是仅查找重复的单词及其计数。我被困在一个地方,无法获得适当的输出。我不能使用任何集合和内置工具。我尝试了下面的代码。需要帮助,请帮帮我。
public class RepeatedWord
{
public static void main(String[] args)
{
String sen = "hi hello hi good morning hello";
String word[] = sen.split(" ");
int count=0;
for( int i=0;i<word.length;i++)
{
for( int j=0;j<word.length;j++)
{
if(word[i].equals(word[j]))
{
count++;
}
if(count>1)
System.out.println("the word "+word[i]+" occured"+ count+" time");
}
}
}
}
预期输出:-
the word hi occured 2 time
the word hello occured 2 time
但我得到如下输出:-
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hello occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hello occured 2 time
请帮助我得到我期望的输出。并请解释。这样我也能理解。 提前致谢
【问题讨论】:
-
你可以使用地图吗?
-
@redflar3 没有。只能使用 for 循环。
-
你不能在这些循环中给出打印,因为我们无法找到给定单词的最后一个匹配项。由于同样的原因,我们必须有一些机制来以某种形式存储事件。一个想法的方法是创建一个 Map,每当找到匹配项时,将值存储在 map 中,键为 word,值为 1,如果 word 已经在 Map 中,则可以增加值。
-
另外,OP 中提到的输出并不是真正的输出,因为您只使用了一个
count变量,无论单词如何,它都会保持递增。 -
@redflar3 对于这段代码,我得到的输出与预期不同。
标签: java for-loop count duplicates