[Solved] java.util.NoSuchElementException

Pre-requisite :  Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.NoSuchElementException” because using scanner.next() two times without checking existence of element in file for second scanner.next() element.

Test data in file

Saurabh Gupta 36 "Sr project Lead" Noida
Nagar 34 "Project Lead"


package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerToReadInputFromFile {
	public static void main(String[] args) {
	try {
		// Decalare Scanner and intialize with File input object
		Scanner sc = new Scanner(
		new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
		while (sc.hasNextLine()) {
		} catch (FileNotFoundException ex) {


Saurabh Gupta 36 "Sr project Lead" Noida

 34 "Project Lead"
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:15)

Always use scanner.next() after checking scanner.hasNext()condition. If scanner.hasNext() returning true then only call scanner.next().

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s