由于我是 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
请帮我得到我期望的输出。并请解释。这样我也能理解。 提前致谢
最佳答案
您只需要为外层循环打印结果。此外,您需要避免检查在上一次迭代中已经检查过的单词:
for (int i = 0; i < word.length; i++) {
int count = 0; // reset the counter for each word
for (int j = 0; j < word.length; j++) {
if (word[i].equals(word[j])) {
/* if the words are the same, but j < i, it was already calculated
and printed earlier, so we can stop checking the current word
and move on to another one */
if (j < i) {
break; // exit the inner loop, continue with the outer one
}
count++;
}
}
if (count > 1) {
System.out.println("the word " + word[i] + " occured " + count + " time");
}
}
更新
关于此代码的附加说明:if (j < i) { break; }
i
是我们计算重复的单词的索引,j
是我们比较它的词。因为我们总是从头开始,所以我们知道如果 j < i
的单词相等, 它已经在外循环的早期运行中处理过。
在这种情况下,使用 break
,我们中断内循环,流程在外循环中继续。因为我们没有更新 count
根本上,它仍然是零,因此是打印结果的条件 if (count > 1)
不满意,println
不执行。
单词“hello”的示例,在以下部分使用简单的伪代码。
第一次出现:
count = 0
i = 1, j = 0 --> hello != hi --> do nothing
i = 1, j = 1 --> hello == hello, j is not < i --> count++
i = 1, j = 2 --> hello != hi --> do nothing
i = 1, j = 3 --> hello != good --> do nothing
i = 1, j = 4 --> hello != morning --> do nothing
i = 1, j = 5 --> hello == hello, j is not < i --> count++
count > 1 --> print the result
第二次出现:
count = 0
i = 5, j = 0 --> hello != hi --> do nothing
i = 5, j = 1 --> hello == hello, j < i --> break, we have seen this pair earlier
count is not > 1 --> result not printed
希望这个例子没有让事情变得更复杂
关于java - 使用 for 循环从带计数的句子中找到重复的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798271/