Preventing the NoSuchElementException when reading from a file with no spare line
I am trying to find a way to deal with the NoSuchElementException error thrown by a Scanner object when reading the last item in my text file with NO SPARE LINE. This means that my cursor will end after the last character of the last line in the file
EXAMPLE:
score.txt
[Test;Word|]
[ & ] denotes the start and end of the text file
The | is where the cursor ends.
I know that if my cursor ends a line below it, my Scanner will not throw the NoSuchElementException because there is a nextLine.
What i want to achieve is to ensure that the NoSuchElementException is not thrown when the spare line is missing. Is there a way to prevent the error from occurring besides making sure that the spare line is there?
My Driver class simply calls the method importWordList() from class WordGame.
The code for WordGame is very long so I will only upload the method importWordList() from the class.
public b开发者_JAVA百科oolean 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;
}
The Error that occurs is as Follows:
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)
The error (at mysterywordgame.WordGame.importWordList(WordGame.java:74)) refers to line with the comment ERROR.
I have searched around for ways to prevent the error from occurring, however, all answers were "Make sure there is a spare line at the end of the text file"
Some help will be much appreciated.
As you already consumed the next line with wordAndHint = delimeterS.nextLine();
you have to check for next line again:
if(delimeterS.hasNextLine()){
answer = delimeterS.nextLine();
}else{
answer = "";
}
精彩评论