【问题标题】:Preventing the NoSuchElementException when reading from a file with no spare line从没有备用行的文件中读取时防止 NoSuchElementException
【发布时间】:2011-01-30 12:17:27
【问题描述】:

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

示例:

score.txt

[测试;单词|]

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

该 |是光标结束的地方。

我知道如果我的光标在它下面结束一行,我的 Scanner 将不会抛出 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 一致的行。

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

我们将不胜感激。

【问题讨论】:

    标签: java exception variable-assignment


    【解决方案1】:

    由于您已经使用 wordAndHint = delimeterS.nextLine(); 消费了下一行,因此您必须再次检查下一行:

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

    【讨论】:

    • 非常感谢你。这几行代码解决了很多问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多