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

Java编写词频统计程序抛出NoSuchElementException找不到错误原因

问题排查与修复

1. 异常抛出的直接原因

你代码中Scanner的读取判断逻辑不匹配:

  • 循环使用sc.hasNextLine()判断是否还有下一行内容,但循环内部调用sc.next()读取单个单词
  • 当文件存在空行、行末仅包含空白字符的场景时,sc.hasNextLine()会返回true,但此时没有有效单词可以读取,调用sc.next()就会直接抛出java.util.NoSuchElementException
  • 修复方案:将循环条件替换为sc.hasNext(),该方法专门用于判断是否还有可读取的单个单词,和sc.next()匹配使用。

2. 其他隐藏逻辑错误

你当前的单词计数逻辑存在错误,会导致统计结果完全失效:

  • 当遇到已存在的单词需要更新计数时,你调用了wordCount.add(indexOfWord, count),这个API的作用是在指定索引位置插入新元素,而非修改原有位置的元素
  • 这会直接导致words存单词的列表和wordCount存计数的列表长度不一致,后续访问还会触发索引越界异常
  • 修复方案:将插入逻辑替换为wordCount.set(indexOfWord, count),直接修改指定索引位置的计数值即可。

修复后完整代码

package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class Text_analyzer
{
  public static void main(String[] args) throws Exception
  {
        File file = new File("TestFile.txt");

        Scanner sc = new Scanner(file);
        int i = 0, indexOfWord = 0, count = 0;
        List<String> words = new ArrayList<String>();
        List<Integer> wordCount = new ArrayList<Integer>();
 
        // 修复循环条件
        while (sc.hasNext())
        {
         String word = sc.next();
    
          if(words.contains(word))
          {
          indexOfWord = words.indexOf(word);
          count = wordCount.get(indexOfWord);
          count = count+1;
          // 修复计数更新逻辑
          wordCount.set(indexOfWord, count);        
          }
          else
          {
          words.add(i,word);
          wordCount.add(i,1);
          i++;
          }
         }
                  
        sc.close();
        
        int no_of_elements = words.size();
        for(int j = 0; j < no_of_elements; j++)
            // 可自行调整打印内容,当前已附加计数输出方便验证
            System.out.println(words.get(j) + " 出现次数:" + wordCount.get(j));
  }
 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:27:04