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

Java文件单词统计代码异常:目标单词统计结果始终为0求排查

单词统计程序计数始终为0的问题排查

问题描述

我需要读取WORDLIST.txt文件,统计用户输入单词在文件中的出现次数——输入单词后返回其出现次数(例如输入long时,返回其在WORDLIST.txt中出现24次)。但编写的Java代码运行后统计结果始终为0,输入long后程序提示该单词出现0次,请求排查问题。

原代码

public static void main(String[] args) 
{
    //creating scanner objects which  will be used to read in the file
    FileReader file = null;
    BufferedReader br = null;
    
    //declaring variables and assigning values
    Scanner szKeyboard = new Scanner (System.in);
    String szWord = "";
    String szSearch;
    int iCount = 0;
    
    try
    {
        //open the file WORDLIST.txt using the Scanner and File classes
        //File object used to open and store the file
        //Scanner object will be used to read through the file object
        file = new FileReader("WORDLIST.txt");
        
        //needed for methods
        br = new BufferedReader(file);
        
        //ask the user what word they're searching for
        System.out.print("What word are you searching for? ");
        szWord = szKeyboard.nextLine();
        System.out.println("Searching the file...");
        
        szSearch = br.readLine();
        
        //method to count how many times that word occurs in the WORDLIST.txt file
        while (szSearch.contains(szWord))
        {
            iCount = iCount + 1;
        }
        
        System.out.println("The word " + szWord  + " appears " + iCount + " times in the file WORDLIST.txt.");
        
    }//end try
    catch (Exception e)
    {
        System.out.println("Error - Writing to File: " + e);
    }//end catch
    finally
    {
        //close scanner
        szKeyboard.close();

        //finally runs regardless of wheter the try has worked
        //the aim of a finally is to tidy up any loose ends
        //if the contents within read is not equal to nothing i.e. it was possible to open and read
        //close the file (try) if the file was not loaded catch the exception IOException
        try
        {
            br.close();
    `your text` }
        catch(IOException e)
        {
            System.out.println("Error - Closing BufferReader: " + e);
        }

        try
        {
            file.close();
        }
        catch(IOException e)
        {
            System.out.println("Error - closing FileReader: " + e);
        }
        System.out.println("\n\n--- File End ---");
    }//end try catch finally`
    
}//end class

运行输出(中文翻译)

你要搜索哪个单词?long
正在搜索文件...
单词long在WORDLIST.txt文件中出现0次。
--- 文件结束 ---

问题分析

  1. 循环逻辑错误:仅读取文件第一行后就进入循环,若第一行不包含目标单词则直接计数为0;若包含则陷入无限死循环(循环内未读取下一行,szSearch值始终不变)。
  2. 未遍历全部文件内容:只检查了文件的第一行,没有读取后续所有行进行统计。
  3. 单词匹配不精准:contains()方法会匹配子串(如搜索"long"时,"longer"会被误判为匹配),不符合“统计完整单词出现次数”的需求。
  4. 语法错误:finally块中br.close()代码行存在多余的your text标记,会导致编译失败。

修正后的代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordCounter {
    public static void main(String[] args) {
        FileReader file = null;
        BufferedReader br = null;
        Scanner szKeyboard = new Scanner(System.in);
        String szWord = "";
        String szSearch;
        int iCount = 0;

        try {
            file = new FileReader("WORDLIST.txt");
            br = new BufferedReader(file);

            System.out.print("你要搜索哪个单词?");
            szWord = szKeyboard.nextLine();
            System.out.println("正在搜索文件...");

            // 编译正则表达式,匹配完整单词(避免子串误判)
            Pattern pattern = Pattern.compile("\\b" + Pattern.quote(szWord) + "\\b");

            // 逐行读取文件直到结束
            while ((szSearch = br.readLine()) != null) {
                Matcher matcher = pattern.matcher(szSearch);
                // 统计当前行中目标单词的出现次数
                while (matcher.find()) {
                    iCount++;
                }
            }

            System.out.println("单词 " + szWord + " 在WORDLIST.txt文件中出现 " + iCount + " 次。");

        } catch (Exception e) {
            System.out.println("文件读取错误:" + e.getMessage());
        } finally {
            szKeyboard.close();
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                System.out.println("关闭BufferedReader错误:" + e.getMessage());
            }
            try {
                if (file != null) file.close();
            } catch (IOException e) {
                System.out.println("关闭FileReader错误:" + e.getMessage());
            }
            System.out.println("\n\n--- 文件结束 ---");
        }
    }
}

关键修改说明

  • 修正循环逻辑:通过while ((szSearch = br.readLine()) != null)逐行读取文件,直到文件末尾。
  • 精准匹配单词:使用正则表达式\\b匹配单词边界,结合Pattern.quote()避免特殊字符干扰,确保只统计完整单词。
  • 统计每行单词次数:用Matcher.find()遍历当前行的所有匹配项,累加计数。
  • 修复语法错误:移除原代码中的无效标记,添加空指针判断避免关闭未初始化的流。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:55:19