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
相关产品推荐
相关产品推荐

