Thursday, September 28, 2023

How to solve java.util.NoSuchElementException in Java? Example

How to fix java.util.NoSuchElementException in Java

java.util.NoSuchElementException is a RuntimeException that can be thrown by different classes in Java like Iterator, Enumerator, Scanner, or StringTokenizer. All of those classes have a method to fetch the next element or next tokens if the underlying data structure doesn't have any element Java throws "java.util.NoSuchElementException". The most common example of this is iterating over hashmap without checking if there is an element or not and that's why it's advised to use hashNext() before calling next() on Iterator. In this Java tutorial we will what causes NoSuchElementException in Java and how to avoid it completely.

Cause of Exception in thread "main" java.util.NoSuchElementException in Java:

How to solve java.util.NoSuchElementException in Javahere are possible cause of java.util.NoSuchElementException in Java:

1) As per Javadoc NoSuchElementException is thrown if you call the nextElement() method of Enumeration and there is no more element in Enumeration. below code will throw java.util.NoSuchElementException because the Enumeration of hashtable is empty.

public class NoSuchElementExceptionDemo{

    public static void main(String args[]) {
        Hashtable sampleMap = new Hashtable();
        Enumeration enumeration = sampleMap.elements();
        enumeration.nextElement();  //java.util.NoSuchElementExcepiton here because enumeration is empty
    }
}

Output:
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
        at java.util.Hashtable$EmptyEnumerator.nextElement(Hashtable.java:1084)
        at test.ExceptionTest.main(NoSuchElementExceptionDemo.java:23)


And, If you are new to the Java world then I also recommend you go through these Java Programming courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.


Here is another example of a java.util.NoSuchElementException which will be thrown because we are calling next() method of Iterator which doesn't contain any element:

public class NoSuchElementExceptionExample {

    public static void main(String args[]) {
        HashMap sampleMap = new HashMap();
        Iterator itr = sampleMap.keySet().iterator();
        itr.next();  //java.util.NoSuchElementExcepiton here because iterator is empty
    }
}

Exception in thread "main" java.util.NoSuchElementException
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:796)
        at java.util.HashMap$KeyIterator.next(HashMap.java:828)
        at test.NoSuchElementExceptionExample.main(ExceptionTest.java:22

In order to avoid these NoSuchElementException always call Iterator.hasNext() or Enumeration.hasMoreElements() before calling next() or nextElement() method.

java.util.StringTokenizer can also throw NoSuchElementException if there is no more token or element and you call the nextToken() or nextElement() method. 

Here is an example of java.util.NoSuchElementException while using StringTokenizer in Java


import java.util.StringTokenizer;

public class StringTokenizerDemo {
    public static void main(String args[]) {
        StringTokenizer tokenReader = new StringTokenizer("", ":");
        System.out.println(tokenReader.nextToken());
    }
}

Exception in thread "main" java.util.NoSuchElementException
        at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
        at test.ExceptionTest.main(StringTokenizerDemo.java:23)


To get rid of this exception while using Stringtokenizer call hasMoreTokens() or hashMoreElements() before proceeding to call nextToken() or nextElement().

here is modified code that will not throw java.util.NoSuchElementException even if there is no more element because it's safeguarded forms hashMoreTokens() method which returns true if there is more tokens available.

 StringTokenizer tokenReader = new StringTokenizer("", ":");
 while (tokenReader.hasMoreTokens()) {
   System.out.println(tokenReader.nextToken());
 }


We have seen possible causes of java.lang.NoSuchElementException in Java can come while using Iterator or Enumeration or StringTokenizer. Best way to fix NoSuchElementException in java is to avoid it by checking Iterator with hasNext(), Enumeration with hashMoreElements() and StringTokenizer with hashMoreTokens().

Some Java Tutorials you may like:
How to use a transient variable in Java

Now lastly one question for you? When was the last time you used StringTokenizer? Do you prefer to use String.split() or StringTokenizer? 

10 comments :

Anonymous said...

My programe was throwing "java.util.nosuchelementexception hashtable enumerator" and I was clueless about it. your tutorial helped me.

Anonymous said...

I have check hasNext() Then also this error is coming

Anonymous said...

Most probably you are calling next() method more than "the number of existing elements" inside the loop.

Burçak

bstpanchkula said...

Thanks . The problem was I was not using hasNext()/hasPrevoius().

Unknown said...

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

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t;
t=sc.nextInt();
while(t>0)
{
int n,k,i;
int count=0;
n=sc.nextInt();
k=sc.nextInt();
Long[] a=new Long[(int) n];
for(i=0;i0&&a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
count++;
j--;
}
}
if(count==k)
{
System.out.println("no");

}
else
{
System.out.println("yes");
}
t--;

}// your code goes here
}
}






















why i am geting this error how can i get rid of this

javin paul said...

It seems you code is not complete, I see a lot of white space in the end, also cna you post the error, which contains line number that will help

Anonymous said...

import java.util.*;
public class LinkedList{
Node head;
class Node{
int data;
Node next;
Node(int d){
data=d;
next=null;
}
}
public void push(int new_data){
Node new_node=new Node(new_data);
new_node.next=head;
head=new_node;
}
public void print(){
Node tNode=head;
while(tNode!=null){
System.out.println(tNode.data+" ");
tNode=tNode.next;
}
}
public static void main(String[] args) {
int ele;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number of elemnts u want to insert in the linked list");
int n=sc.nextInt();
LinkedList l=new LinkedList();
for(int i=0;i<n;i++){
if(sc.hasNextInt()){
ele=sc.nextInt();
l.push(ele);
}
}
l.print();
}
}

Error:
Enter the number of elemnts u want to insert in the linked list
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 LinkedList.main(LinkedList.java:28)



why this error?

javin paul said...

Hello Anonymous, can you explain more, what is your issue and what are you trying to do?

Unknown said...

import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.util.StringTokenizer;
class PercentageExDemo
{
public static void main(String args[])throws IOException,PercentageException
{
FileReader fr=new FileReader("data.txt");
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter("op.txt");
BufferedWriter bw=new BufferedWriter(fw);
String line="";
while((line=br.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(line,"");
String name=st.nextToken();
int age=Integer.parseInt(st.nextToken());
float per=Float.parseFloat(st.nextToken());
Student s1=new Student(name,age,per);
try
{
s1.checkPercentage();
bw.write(s1+"\n");
}
catch(PercentageException p)
{
System.out.println(p);
}

}
fr.close();
br.close();
bw.close();
fw.close();
}
}
class Student
{
String name;
int age;
float percentage;
Student(String name,int age,float per)
{
this.name=name;
this.age=age;
this.percentage=per;
}
public String toString()
{
return name+""+age+""+percentage;
}
void checkPercentage()throws PercentageException
{
if(percentage<50)
throw new PercentageException(percentage);

}

}
class PercentageException extends Exception
{
float percentage;
PercentageException(float per)
{
this.percentage=per;
}
public String toString()
{
return "Percentage Eception.Below["+percentage+"]";
}

}
MY PROBLEMS IS
JAVA.UTILE.NoSuchAElementException
kindly I'm asking please help me to solve this problem......

Anonymous said...

Mee too. What should I do to solve the error

Post a Comment