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

Java使用Scanner的hasNextLine()读取文件出现No Line found异常问题排查

报错原因
  • 外层while(inFile.hasNextLine())仅在进入循环前做一次行存在性校验,你在循环内部嵌套了遍历26个字母的for循环,每次循环直接调用inFile.nextLine()读取行,过程中没有再校验是否还有剩余行,只要文件行数小于26,for循环执行到后半段就会触发无行可读的异常。
  • 额外潜在问题:如果单行单词数超过你定义的MAX_WORDS=10,后续给synonyms数组赋值时会触发下标越界异常。
修复方案

调整逻辑,每次读取行前都做校验,匹配synonyms数组的下标规则写入:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class LabProgram {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      int NUM_CHARACTERS = 26;      // Maximum number of letters
      int MAX_WORDS = 10;           // Maximum number of synonyms per starting letter
      String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
      char userChar = scnr.next().charAt(0); //Get char user wants to search
      String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS];  // Declare 2D array for all synonyms
      
      File aFile = new File(userWord);
      Scanner inFile = new Scanner(aFile);
      
      int lineIndex = 0;
      // 每次读行前都校验,同时不超过数组最大容量
      while(inFile.hasNextLine() && lineIndex < NUM_CHARACTERS) {
          String[] words = inFile.nextLine().trim().split(" ");
          // 单行单词数不超过数组最大长度,避免越界
          int validWordCount = Math.min(words.length, MAX_WORDS);
          for(int wordCount = 0; wordCount < validWordCount; wordCount++) {
              synonyms[lineIndex][wordCount] = words[wordCount];
          }
          lineIndex++;
      }
      inFile.close();
      scnr.close();
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:36:01