使用for循环从句子中找到重复的单词(没有内置函数)

时间:2015-09-26 12:30:15

标签: java for-loop count duplicates

由于我是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;i<word.length;j++)
                   {
                       if(word[i]==word[j])
                          {
                             count++;
                          }
                System.out.println("the word "+word[i]+" occured"+ count+" time");
                   }

             }

       }
 }

1 个答案:

答案 0 :(得分:0)

将字符串与equals()进行比较,而不是==

if(word[i].equals(word[j]))

==比较了参考 equals()比较该对象的值。

除了第二个循环应该有j<word.length

将代码更改为

String sen = "hi hello hi good morning hello";
String word[] = sen.split(" ");
int count = 0;
for (int i = 0; i < word.length; i++) {
    count = 0;
    for (int j = 0; j < word.length; j++) {

        if (word[i].equals(word[j])) {
            count++;
        }

    }
    if(count>1)   //show only duplicate word
    System.out.println("the word " + word[i] + " occured " + count + " time");
}

DEMO