How to Fix the NoSuchElementException Error in Java

Mohammad Irfan Feb 02, 2024
  1. NoSuchElementException While Using Iterator in Java
  2. NoSuchElementException While Using Enumeration in Java
  3. NoSuchElementException While Using StringTokenizer in Java
  4. NoSuchElementException While Using Scanner Class in Java
How to Fix the NoSuchElementException Error in Java

An exception is an event that happens during a program’s execution. The normal program flow is affected when an exception occurs, and the program terminates abnormally. This tutorial will discuss java.util.NoSuchElementException and how to handle it in Java.

The NoSuchElementException inherits from the RuntimeException class, which means it’s an unchecked Exception. Unchecked Exceptions are not handled by the compiler, as they happen during runtime.

The NoSuchElementException is thrown by Scanner class, Iterator interface, Enumerator interface, and StringTokenizer class. These classes have accessors’ methods to fetch the next element from an iterable. They throw NoSuchElementException if the iterable is empty or has reached the maximum limit.

Let’s look at how different classes throw NoSuchElementException.

NoSuchElementException While Using Iterator in Java

The Iterator interface has a method called next() used to access the next element in the iteration. If no element is in the collection, then NoSuchElementException is thrown. We will look at some examples.

Trying to iterate a HashMap with no elements:

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    // creating a hashmap with no element
    HashMap<String, Integer> h1 = new HashMap<>();
    // creating an iterator object
    Iterator i = h1.keySet().iterator();
    // trying to access element
    i.next();
  }
}

Output:

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1599)
    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1620)
    at MyClass.main(MyClass.java:9)

The next() method throws an exception because the HashMap is empty. We can use the hasNext() method to avoid this exception; it returns true if the iterable has more elements.

We should use the next() method only if hasNext() returns True, to avoid such exceptions. See the example below.

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    // creating a hashmap with no element
    HashMap<String, Integer> h1 = new HashMap<>();
    // creating an iterator object
    Iterator i = h1.keySet().iterator();
    // trying to access element
    while (i.hasNext()) {
      i.next();
    }
  }
}

This code throws no exception. Let’s take an example with some elements in the HashMap and iterate the elements.

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    // creating a hashmap
    HashMap<String, Integer> h1 = new HashMap<>();
    h1.put("one", 1);
    h1.put("two", 2);
    // creating an iterator object
    Iterator i = h1.keySet().iterator();
    // trying to access element
    while (i.hasNext()) {
      System.out.println(i.next());
    }
  }
}

Output:

one
two

Without the hasNext() method, this code would have thrown an exception, but it’s working fine.

NoSuchElementException While Using Enumeration in Java

In Java, Enumeration has a method called nextElement() that returns the next element of the enumeration. If there’s no element to return, it throws a NoSuchElementException.

Look at the example below where we are creating an enum from a list.

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    ArrayList<String> animals = new ArrayList<>();
    animals.add(new String("elephant"));
    // creating enumeration object
    Enumeration en = Collections.enumeration(animals);
    System.out.println(en.nextElement()); // gets "elephant"
    System.out.println(en.nextElement()); // throws exception
  }
}

Output:

elephant

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
    at java.base/java.util.Collections$3.nextElement(Collections.java:5440)
    at MyClass.main(MyClass.java:9)

The hasElement() throws an exception after returning the first element because no elements are left in the ArrayList to be accessed. We can use the hasMoreElements() method to avoid this situation.

This method returns true if there are more elements in the enumeration to provide; else, it returns false. We can call the nextElement() method only if there are more elements in the enumeration.

Look at the example below:

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    ArrayList<String> animals = new ArrayList<>();
    animals.add(new String("elephant"));
    // creating enumeration object
    Enumeration en = Collections.enumeration(animals);
    while (en.hasMoreElements()) {
      System.out.println(en.nextElement()); // gets "elephant"
    }
  }
}

Output:

elephant

NoSuchElementException While Using StringTokenizer in Java

In Java, StringTokenizer class provides two methods, the nextToken() and nextElement(). The nextToken() method returns the next token(string type) from the string tokenizer, whereas the nextElement method is like the nexttoken() except that it returns an object type rather than a string. Both methods throw the NoSuchElementException.

See the example below.

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    String s = "I Love Delft";
    StringTokenizer st = new StringTokenizer(s);
    System.out.println(st.nextToken()); // gets I
    System.out.println(st.nextToken()); // gets Love
    System.out.println(st.nextToken()); // gets Delft
    System.out.println(st.nextToken()); // Throws exception
  }
}

Output:

I
Love
Delft

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:347)
    at MyClass.main(MyClass.java:9)

We can avoid the exception using the hasMoreTokens() and hasMoreElements() method. Both methods return true if more tokens are available in the tokenizer’s string. We should call the nextToken() method only if hasMoreTokens() method returns True.

See the example below:

import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    String s = "I Love Delft";
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
      System.out.println(st.nextToken());
    }
  }
}

Output:

I
Love
Delft

NoSuchElementException While Using Scanner Class in Java

The Scanner class in Java provides several utility methods such as next(), nextInt(), etc. While working with these methods, they can throw the NoSuchElementException. We will discuss them here.

  1. Suppose you have two scanner objects accessing the Standard Input. If you close one of them and call a method using the other one, it throws the NoSuchElementException. See the example below.
import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    String s = "I Love Delft";
    Scanner s1 = new Scanner(System.in);
    Scanner s2 = new Scanner(System.in);
    s1.close();
    s2.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 MyClass.main(MyClass.java:8)

When we close the first Scanner, it closes the underlying InputStream; therefore, the second Scanner can’t read from the same InputStream and throws a NoSuchElementException. The solution is to use one scanner object to read System.in input.

  1. Suppose you’re reading a string or a file using the scanner object. If there’s no line left to read, an exception shows. See the example below.
import java.util.*;
public class MyClass {
  public static void main(String args[]) {
    String s = "I Love Delft";
    Scanner s1 = new Scanner(s);
    System.out.println(s1.nextLine());
    System.out.println(s1.nextLine());
  }
}

Output:

I Love Delft

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at MyClass.main(MyClass.java:7)

To solve this problem, we use the hasNextLine() method that returns a Boolean value. Look at the example.

import java.util.*;
public class Main {
  public static void main(String args[]) {
    String s = "I Love Delft";
    Scanner s1 = new Scanner(s);
    while (s1.hasNextLine()) {
      System.out.println(s1.nextLine());
    }
  }
}

Output:

I Love Delft

Related Article - Java Error