Tag Archives: NoSuchElementException

[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().

Advertisements

[Solved]java.util.NoSuchElementException


java.util.NoSuchElementException is runtime unchecked exception which throws by  nextElement() method of an Enumeration or nextXYZ() method of Scanner to indicate that there are no more elements in the enumeration or scanner.

Constructors

  • NoSuchElementException() : Constructs a NoSuchElementException with null as its error message string.
  • NoSuchElementException(String s) : Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage() method.

Example  NoSuchElementException

In below example NoSuchElementException occured because using useDelimiters(“\sGaurav\s“) while in test input using delimiters as “Saurabh”. In that case scanner will have only one text line and not split. When we retrieve data from scanner will throw this NoSuchElementException.

import java.util.Scanner;
public class JavaScannerParsingExample {
	public static void main(String[] args) {
		String input = "Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh";
	     Scanner s = new Scanner(input).useDelimiter("\s*Gaurav\s*");
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.nextInt());
	     System.out.println(s.nextInt());
	     s.close();
	}
}

Output

Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:11)

Solutions

  • In case of enumeration always check for hasNextElement() before use method next() to retrieve element of enumeration.
  • In case of Scanner always check for hasNext() before use method nextXYZ() to retrieve values from scanner.

References

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

[Solved]java.util.InputMismatchException


java.util.InputMismatchException which throw by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

  • InputMismatchException is runtime unchecked exception.
  • InputMismatchException is sub class of NoSuchElementException.

Constructors

  • InputMismatchException() : Constructs an InputMismatchException with null as its error message string.
  • InputMismatchException(String s): Constructs an InputMismatchException, saving a reference to the error message string s for later retrieval by the getMessage method.

Example

In below example create this java.util.InputMismatchException by passing some others type values other than expectation. For Example : age expected as integer value from console while passing as decimal value.

import java.util.Scanner;

public class JavaScannerExample {

	public static void main(String[] args) {
		// Create a Scanner object
		Scanner scanner = new Scanner(System.in); 

		try
		{
		//User different type of input from console
		System.out.println("Please enter user name:");
		String userName = scanner.nextLine();
		System.out.println("Please enter age:");
		int age = scanner.nextInt();
		System.out.println("Please enter salary:");
	    double salary = scanner.nextDouble();

	    //Output input by user
	    System.out.println("User Name: " + userName);
	    System.out.println("Age: " + age);
	    System.out.println("Salary: " + salary);
		}
		catch(Exception ex)
		{
			System.err.println("Entered user input are not match with required type:");
			ex.printStackTrace();
		}

	}

}
Please enter user name:
Saurabh Gupta
Please enter age:
13.5
Entered user input are not match with required type:
java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at com.userinput.JavaScannerExample.main(JavaScannerExample.java:28)

Solution

  • In such type scenarios where user interaction required always write code and ask input as scanner.nextLine();
  • Always validate values type before assign to variable.
  • If any mismatch found and throw above exception show message to insert value again as required format.

References

https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s