You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java统计字符串重复单词的代码为什么每个值计数都为1?

问题原因
  • Java中==用于引用类型比较时,判断的是两个对象的内存地址是否相同,而非对象存储的内容。String属于引用类型,split()方法切分得到的每个字符串都是独立的新对象,即便两个单词内容完全一致,内存地址也不相同。
  • 原有代码中if(arr[i] == arr[j])只有当i=j、比较的是同一个对象时才会返回true,因此每个单词的统计结果都是1。
修复方案

方案1:修改原有双重循环逻辑

仅需将字符串比较的判断条件改为调用equals()方法对比内容即可,适合小体量字符串场景:

import java.util.*;
public class MyClass {
    public static void main(String args[]) 
    {
        Scanner scn = new Scanner(System.in);
        String str = scn.nextLine();
        String[] arr = str.split(" ");
        for(int i =0; i<arr.length; i++)
        {
            int count = 0;
            for(int j =0; j<arr.length; j++)
            {
                // 改为equals比较字符串内容
                if(arr[i].equals(arr[j]))
                {
                    count++;
                }
            }
            System.out.print(count + " ");
        }
    }
}

注意:该方案时间复杂度为O(n²),单词数量较多时运行效率较低。

方案2:使用HashMap实现高效计数(推荐)

通过哈希表存储单词和对应出现次数,仅需遍历一次数组即可完成统计,时间复杂度为O(n):

import java.util.*;
public class MyClass {
    public static void main(String args[]) 
    {
        Scanner scn = new Scanner(System.in);
        String str = scn.nextLine();
        String[] arr = str.split(" ");
        Map<String, Integer> wordCount = new HashMap<>();
        // 遍历统计
        for (String word : arr) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
        // 输出结果,可按需调整输出格式
        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

内容的提问来源于stack exchange,提问作者anuj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:48:05