java - 从没有备用行的文件读取时防止出现 NoSuchElementException

标签 java exception variable-assignment

我正在尝试找到一种方法来处理在没有备用行的情况下读取文本文件中的最后一项时 Scanner 对象引发的 NoSuchElementException 错误。这意味着我的光标将在文件最后一行的最后一个字符之后结束

示例:

分数.txt

[测试;单词|]

[ & ] 表示文本文件的开始和结束

|是光标结束的位置。

我知道,如果我的光标在其下方结束一行,我的扫描仪将不会抛出 NoSuchElementException,因为有一个 nextLine。

我想要实现的是确保当备用行丢失时不会抛出NoSuchElementException。除了确保有备用线之外,还有其他方法可以防止错误发生吗?

我的 Driver 类只是从 WordGame 类调用 importWordList() 方法。

WordGame 的代码很长,因此我只上传类中的 importWordList() 方法。

public boolean importWordList(String fileName) throws FileNotFoundException
{
    //Set default return value
    boolean returnVal = false;

    //Set File to read from
    File wordListDest = new File(fileName);

    if (wordListDest.canRead() == true)
    {
        lineS = new Scanner(wordListDest);

        //Read each line from file till there is no line
        while (lineS.hasNextLine())
        {

            //Set delimeter scanner to use delimeter for line from line scanner
            String line = lineS.nextLine();
            delimeterS = new Scanner(line);
            delimeterS.useDelimiter(";");

            //Read each delimeted string in line till there is no string
            while (delimeterS.hasNextLine())
            {

                //Store Variables for quiz object
                wordAndHint = delimeterS.nextLine();
                answer = delimeterS.nextLine();               //ERROR

                //Create Object Quiz and add to wordList
                Quiz addWord = new Quiz(wordAndHint, answer);
                wordList.add(addWord);
            }
            delimeterS.close();
        }
        lineS.close();
        returnVal = true;
        System.out.println("Word List has been Imported Successfully!");
    }
    else
    {
        System.out.println("The file path you selected either does not exist or is not accessible!");
    }
    return returnVal;
}

出现的错误如下:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1516)
    at mysterywordgame.WordGame.importWordList(WordGame.java:74)
    at mysterywordgame.Main.main(Main.java:60)

错误(位于 MysteryWordGame.WordGame.importWordList(WordGame.java:74))是指带有注释 ERROR 的行。

我已经四处寻找防止错误发生的方法,但是,所有答案都是“确保文本文件末尾有备用行”

我们将不胜感激一些帮助。

最佳答案

因为您已经使用 wordAndHint = delimeterS.nextLine(); 消耗了下一行您必须再次检查下一行:

if(delimeterS.hasNextLine()){     
   answer = delimeterS.nextLine();     
}else{
   answer = "";
}

关于java - 从没有备用行的文件读取时防止出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4842835/

相关文章:

java - 如何使用 STAX 事件驱动或流 API 解析未知的 XML 结构

c - 初始化数组 - 警告 : assignment makes integer from pointer without a cast

python - 为不同的 ndarray 索引分配相同的值 - Python

c++ - 如何使子类与 C++ 中的父类互换?

java - Spring中的路径属性

java - 如何创建一个只能添加单一类型且不允许添加子类或父类(super class)的 Set?

java - 如何选择 ArrayList<List> 中列表的哪一列用于对 ArrayList 进行排序?

java - 使用匿名线程捕获异常

java - 如何在 Graphics 中成功使用 Thread.sleep() 方法?

java - 与 Weblogic JMS 队列的连接失败