[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
Sailesh
Nagar 34 "Project Lead"

Example

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()) {
		   System.out.println(sc.nextLine());
		   System.out.println(sc.next());
		   //System.out.println(sc.next(Pattern.compile("\\w+")));
			}
		} catch (FileNotFoundException ex) {
		    ex.printStackTrace();
		}
	}
}

Output

Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh

Nagar
 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)


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