Home » Java Basics » exceptions » java.util.NoSuchElementException – How to solve NoSuchElementException

About Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas
Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

java.util.NoSuchElementException – How to solve NoSuchElementException

In this tutorial we will discuss about NoSuchElementException in Java. This exception is thrown to indicate that there are no more elements in an enumeration.

This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.

Finally, the NoSuchElementException exists since the first version of Java.

 

The Structure of NoSuchElementException

Constructors

  • NoSuchElementException()
  • Creates an instance of the NoSuchElementException class, setting null as its message.

  • NoSuchElementException(String s)
  • Creates an instance of the NoSuchElementException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The NoSuchElementException in Java

The NoSuchElementException can be thrown by the following methods:

All the aforementioned methods try to return the next element of an enumeration and throw that exception, in order to indicate that no more elements exist. A sample example that throws a NoSuchElementException is the following:

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.StringTokenizer;

public class NoSuchElementExceptionExample {
	public static void main(String[] args) {
		Set sampleSet = new HashSet();
		Hashtable sampleTable = new Hashtable();
		StringTokenizer tokenizer = new StringTokenizer("", ":,");
		
		/* All following statements throw a NoSuchElementException. */
		sampleSet.iterator().next();
		sampleTable.elements().nextElement();
		tokenizer.nextToken();
	}
}

A sample execution is shown below:

Exception in thread "main" java.util.NoSuchElementException
	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1431)
	at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
	at main.java.NoSuchElementExceptionExample.main(NoSuchElementExceptionExample.java:15)

How to deal with the NoSuchElementException

A very common error case is when a Java application tries to iterate over an empty Set. In order to avoid this error, a Java application should call the hasNext first. For example:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MapIterationExample {
	private final static int TOTAL_ELEMENTS = 100;
	
	public static void main(String[] args) {
		Set sampleSet = new HashSet(TOTAL_ELEMENTS);
		
		Iterator ite = sampleSet.iterator();
		while(ite.hasNext())
			System.out.println(ite.next());
	}
}

Accordingly, if a Java application uses enumerations, the hasMoreElements method shall be used:

import java.util.Enumeration;
import java.util.Hashtable;

public class EnumerationIterationExample {
	private final static int TOTAL_ELEMENTS = 100;
	
	public static void main(String[] args) {
		Hashtable sampleTable= new Hashtable(TOTAL_ELEMENTS);

		Enumeration tableEnum = sampleTable.elements();
		while(tableEnum.hasMoreElements())
			System.out.println(tableEnum.nextElement());
	}
}

Finally, a proper user of the StringTokenizer is the following:

import java.util.StringTokenizer;

public class StringTokenizerExample {
	public static void main(String[] args) {
		String str = "Hello:from:Java,Code:Geeks";
		StringTokenizer tokenizer = new StringTokenizer(str, ":,");
		
		while(tokenizer.hasMoreTokens())
			System.out.println(tokenizer.nextToken());
	}
}

Download the Eclipse Project

The Eclipse project of this example: NoSuchElementExceptionExample.zip.

 
This was a tutorial about the NoSuchElementException in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
priya
priya
1 year ago

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();

while(t>0)
{
int n = sc.nextInt();

int[] arr = new int[n];
int count = 0;
for(int i = 0 ; i<n;i++)
{
arr[i] = sc.nextInt();
}
for( i = 0 ; i<n-1 ; i++)
{
for(int j = i+1 ; j<n ; j++)
{
if(arr[i] < arr[j])
{
count = 1;
}
}
if(count == 0)
{
System.out.print(arr[i] + " ");
}
}
}

}
}
it shows no such element exception

amit
amit
1 month ago

getting error
Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Codechef.main(Main.java:15)

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{

Scanner sc = new Scanner(System.in);

int N = sc.nextInt();

int s[] = new int[N];
for(int j=0; j<N; j++){
  s[j] = sc.nextInt();
}
sc.close();

int temp = 0;
for(int i=0; i<s.length-1; i++){
  if(s[i]<s[i+1]){
    temp = temp+((s[i+1]-s[i])-1);
  }else{
    temp = temp+((s[i]-s[i+1])-1);
  }
}System.out.println(temp);

}
}