我正試圖找到一種方法來處理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