我正试图找到一种方法来处理Scanner对象在读取我的文本文件中的最后一项时使用NO SPARE LINE引发的NoSuchElementException错误。这意味着,我的光标在最后一行的文件中的最后一个字符之后结束从没有备用行的文件读取时防止出现NoSuchElementException错误
例:
score.txt
[测试;单词|]
[&]表示文本文件的开始和结尾
The |是光标结束的地方。
我知道如果我的光标在它下面结束一行,我的扫描器将不会抛出NoSuchElementException,因为存在nextLine。
我想实现的目的是确保在备用行丢失时不会引发NoSuchElementException。除了确保备用线路在那里之外,是否有办法防止发生错误?
我的驱动程序类只是从类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到线路。
...我已经寻找周围的方式来防止错误的发生,但是,所有的答案是“确保有在文本文件的最后一个备用线”
一些帮助将非常感激。
非常感谢您morja。这几行代码解决了很多问题。 – Muhammad 2011-01-30 12:41:23