java-使用for循环从具有计数的句子中找到重复的单词

由于我是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 <j时这些词相等.我,它已经在外部循环的早期运行中进行了处理. 在这种情况下,使用break中断内部循环,并且流程继续在外部循环中进行.由于我们根本没有更新计数,所以它仍然为零,因此如果(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

希望我不会让这个例子变得更复杂

上一篇:python-drop_duplicates在熊猫中不起作用?


下一篇:哪个Java集合允许重复的键