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

Java读取TXT文件统计单词出现次数问题求助:代码始终返回0的排查

解决Java统计《白鲸记》单词出现次数始终为0的问题

Hey there! Let's break down why your word count is always showing 0—this is a super common gotcha with Java strings, so we'll get this fixed in no time.

核心问题1:错误的字符串比较方式

The biggest issue here is how you're comparing strings. In Java, == checks if two string objects are the same in memory, not if their content matches. Even if nextWord and userWord have identical text, they're separate objects, so == will always return false.

You need to use the equals() method instead, which compares the actual string content. If you want to ignore case (like matching "Moby" and "moby"), use equalsIgnoreCase() instead.

核心问题2:未处理文本中的标点

The text from Moby Dick probably has words attached to punctuation (like "Moby," or "Dick."). When you read these with input.next(), the punctuation gets included, so it won't match the clean word the user inputs. We can fix this by stripping non-alphabetic characters from each word we read.

修正后的代码

Here's your updated code with these fixes, plus a small improvement to auto-close your scanners using try-with-resources (to avoid resource leaks):

import java.util.*;
import java.io.FileNotFoundException;

public class MobyDick {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("What word would you like to search for?");
        
        // Use try-with-resources to auto-close scanners
        try (Scanner userInput = new Scanner(System.in);
             Scanner input = new Scanner(new File("mobydick.txt"))) {
            
            String userWord = userInput.nextLine().trim();
            int wordCount = 0;
            
            while (input.hasNext()) {
                String nextWord = input.next();
                // Strip non-alphabetic characters and convert to lowercase
                String cleanedWord = nextWord.replaceAll("[^a-zA-Z]", "").toLowerCase();
                String normalizedUserWord = userWord.toLowerCase();
                
                if (cleanedWord.equals(normalizedUserWord)) {
                    wordCount += 1;
                }
            }
            System.out.println("The total number of '" + userWord + "' in Moby Dick is " + wordCount);
        }
    }
}

关键改动说明

  • 把==换成了基于小写归一化后的equals(),既能匹配内容,又忽略大小写差异
  • 用replaceAll("[^a-zA-Z]", "")去掉了读取单词中的标点、数字等非字母字符
  • 使用try-with-resources管理Scanner资源,让它们自动关闭,避免I/O资源泄漏
  • 对用户输入做了trim()处理,去掉可能的首尾空格

Give this a try—you should start seeing accurate word counts now!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:07:48