Home >Java >javaTutorial >How to Avoid 'No Line Found' Exceptions When Using Java's Scanner?
No Line Found Exception: Resolving Scanner Usage
When reading a file using Scanner, it's essential to handle situations where there are no more lines to read. If the Scanner reaches the end of the file without finding a line, it throws a java.util.NoSuchElementException with the message "No line found."
In the provided example, this exception occurs because the code doesn't check if there is a next line before calling sc.nextLine(). To resolve this, the loop should be modified to use hasNextLine() to check for the availability of lines:
while(sc.hasNextLine()){ str=sc.nextLine(); // ... }
Additionally, Readers, unlike Scanners, return null when they reach the end of file. This behavior is not dependent on the input file's format, making it a more reliable approach in certain scenarios.
The above is the detailed content of How to Avoid 'No Line Found' Exceptions When Using Java's Scanner?. For more information, please follow other related articles on the PHP Chinese website!