We will learn how to fix a java.util.NoSuchElementException in Java. First of all, what is an exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. In simple words, an exception is a runtime error.
java.util.NoSuchElementException is a java built-in exception. This exception occurs when trying to access an iterable beyond its maximum limit. This exception is inherited from the RuntimeException class.
java.util.NoSuchElementException is thrown by :
➤ Iterator interface
➤ Scanner class
➤ StringTokenizer class
➤ Enumerator interface
1. java.util.NoSuchElementException while using an iterator
An iterator interface of the Java collections framework allows us to access elements of a collection. This iterator interface has a method called next(), which is used to access the next element in the iteration. If there are no elements preset then, ‘java.util.NoSuchElementException’ is thrown by the compiler.
Code
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
class iteratorException{
public static void main(String[] args){
Set hashSet = new HashSet();
hashSet.iterator().next();
}
}
Output
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1513) at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1534) at iteratorException.main(iteratorException.java:8)
Solution
The solution for this kind of exception is to check whether the next element is present or not.
You should only move to this position if the check returns that the position is not empty. Instead of using the next(), we can use the hasNext() method to resolve the exception.
From the above code:
class iteratorException{
public static void main(String[] args){
Set hashSet = new HashSet();
hashSet.iterator().next();
}
}
Instead the last line (hashSet.iterator().next();), you can write the following (hashSet.iterator().hasNext();) to avoid error:
class iteratorException{
public static void main(String[] args){
Set hashSet = new HashSet();
hashSet.iterator().hasNext();
}
}
2. java.util.NoSuchElementException while using a Scanner class
The Scanner class is used to get user input, and it is found in java.util package. To use the scanner class, a scanner object must be created. When two scanner objects were created and by using the close method, if we close one scanner object and if we use the next method for another scanner object then an exception is raised.
Code
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
sc.close();
sc1.next();
}
}
Output
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478) at Main.main(Main.java:8)
Solution
There are different solutions for different types of inputs. For example, if we are taking a string as an input, then by using a condition we should check whether the scanner object is closed or not by using hasNextLine() method. Here HasNextLine() should return a boolean value.
From the above code:
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
sc.close();
sc1.next();
}
}
Instead the last line (sc1.next();), you can write the following (sc1.hasNextLine();) to avoid error:
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
sc.close();
sc1.hasNextLine();
}
}
3. java.util.NoSuchElementException while using string tokenizer class
StringTokenizer class allows an application to break a string into tokens. In this class, if we call the method nextElement() or nextToken() and there is no element or token present then this exception is raised.
Code
import java.util.StringTokenizer;
class Main{
public static void main(String[] args){
StringTokenizer str = new StringTokenizer("",":");
System.out.println(str.nextToken());
}
}
Output
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)at Main.main(Main.java:6)
Solution
By using a condition to check whether the tokens or elements are present or not by calling a method hasMoreElements() or hasMoreTokens(). If positive then we can use the method nextToken() or nextElement().
a) You always have to check StringTokenizer.hasMoreTokens() first. Throwing NoSuchElementException is the documented behaviour if no more tokens are available:
Example:
token = new StringTokenizer (line);
while(token.hasMoreTokens())
words.add(token.nextToken());
b) Don’t create a new Tokenizer for every line, unless your file is too large to fit into memory. Read the entire file to a String and let the tokenizer work on that.
4. java.util.NoSuchElementException while using the Enumerator interface
Enumeration means a list of named constants. If we call the method nextElement() and there is no element present in the enumeration then this exception is raised.
Code
import java.util.*;
class Main{
public static void main(String[] args){
Hashtable ht = new Hashtable();
Enumeration en = ht.elements();
en.nextElement();
}
}
Output
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Collections$EmptyEnumeration.nextElement(Collections.java:4291) at Main.main(Main.java:6)
Solution
By using a condition to check whether the hast table contains any elements or not by calling a method hasMoreElements(). If positive then we can use the method nextElement().
Example:
while(en.hasMoreElements()) {
System.out.println(en.nextElement());
}
Conclusion
In this article, we have learned about what is an exception, what is a “java.util.NoSuchElementException” in java, various cases where the “java.util.NoSuchElementException” may occur, and how to remove when the “java.util.NoSuchElementException” has encountered.