Java util nosuchelementexception ошибка

An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.

There are mainly two types of exception in java as follows:

1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get the compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.

2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.

Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.

NoSuchElementException:

It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM and given by the accessors methods of Enumeration, Iterator or Tokenizer such as next() or nextElement() or nextToken() when we are trying to access the content of an array, collection, or any other object and if these objects are empty or if we are trying to get next element after reaching the end of an object then we will get java.util.NoSuchElementException.

In the below example we are trying to access a HashMap by using the accessor method next() of the Iterator class but as the HashMap is empty we will be going to get NoSuchElementException.

Example 1:

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        HashMap<Integer, Integer> map = new HashMap<>();

        Iterator itr = map.keySet().iterator();

        itr.next();

    }

}

 
 Output:

Example 2: Here we are trying to access the element of an empty vector object through an enumerator.

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        Vector<Integer> v = new Vector<>();

        Enumeration enumerator = v.elements();

        enumerator.nextElement();

    }

}

 Output:

How to solve this error? 

Almost all the classes whose accessor methods give NoSuchElementException contains their respective method to check whether the object contains more elements or not. So in order to avoid this NoSuchElementException we need to always call,

  • Iterator.hasNext() or
  • Enumeration.hasMoreElements() or
  • hasMoreToken() method before calling next( ) or nextElement or nextToken() method.

Below is the implementation of the above statement :

Example 1:

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        HashMap<Integer, Integer> map = new HashMap<>();

        Iterator itr = map.keySet().iterator();

        while (itr.hasNext())

            System.out.println(itr.next());

    }

}

Output:

 Example 2:

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        Vector<Integer> v = new Vector<>();

        Enumeration enumerator = v.elements();

        while (enumerator.hasMoreElements())

            System.out.println(enumerator.nextElement());

    }

}

Output:

Last Updated :
02 Jun, 2023

Like Article

Save Article

I was trying to program a game of battleship and i ran into this error at the point where the user was prompted to enter their guess coordinates:

Exception in thread "main" java.util.NoSuchElementException


    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 game.User.takeTurn(User.java:121)
        at game.Game.main(Game.java:61)

Here is the method User.takeTurn() where the error occured:

    static void takeTurn() {
           System.out.println("Yout turn!");
           System.out.println("Enter your x guess:");
           Scanner scanInput = new Scanner(System.in);
           int x;
           x = scanInput.nextInt();
           System.out.println("You entered "+ x + ", Now enter your y     coord:");
           int y;
           y = scanInput.nextInt();
           System.out.println("You entered + " + y);
           if(Board.aiBoard[x][y] == 2) {
               System.out.println("Hit! You got a hit at: " + x + "," + y);
               Board.enemyBoardDisplay[x][y] = 'h';
               Board.aiBoard[x][y] = 3;
           }
           else {
            System.out.println("Miss!");
            Board.enemyBoardDisplay[x][y] = 'x';
            Board.aiBoard[x][y] = 1;
          }

           scanInput.close();
      }

Im not really sure if it matters or not but i also use another scanner earlier in the class. If you need more code to help just let me know. Thanks!

edit 1:
Ok, even after I do scanInput.hasNextInt() its not working. I also put in an else statement that gave x a value but now x always has the value that the else statement gives. It dosent even ask for an input it just defaults to that value. But i dont want it to go to a default i want the user to pick.

edit 2: This is where i call the code in my main stub

while (gameOn == true) {
            if (turn == 0) {
                User.takeTurn();
                Board.sunkCheck();
                if (gameOn == false)
                    break;
            }

            else if (turn == 1) {
                Computer.takeTurn();
                Board.sunkCheck();
                if (gameOn == false)
                    break;
            }

This is where i use a scanner earlier in the same class as im trying to use the scanner now:

System.out
                .println("n Please enter the first x value for your ship  (Note, this will be the first point, from this point the n"
                        + " ship can either go vertically downward or horizontally to the right so please choose the topmost point or leftmost n"
                        + "point to do this. Also, the board is 10x10 but due to java array indexing the coordinates go x 0-9 y 0-9: ");
        try {
        Scanner coord = new Scanner(System.in);
        userX = coord.nextInt();
        System.out.println("You entered: " + userX);
        System.out.println("Now enter the y coordinate for this point: ");
        userY = coord.nextInt();
        System.out.println("You entered: " + userY);
        System.out
                .println("Please choose the direction of your ship. Enter v for verticle or h for horizontal(case sensitive): ");
        dir = (char) System.in.read();
        coord.close();
        }
        catch(InputMismatchException e) {
            System.out.println("Good job doof, since you tried to troll we did all the values for you!");
            userX = 3;
            userY = 3;
            dir = 'v';
        }

  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

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:

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:

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:

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:

The NoSuchElementException is an unchecked exception in Java that can be thrown by various accessor methods to indicate that the element being requested does not exist.

Since the NoSuchElementException is thrown at runtime, it does not need to be declared in the throws clause of a method or constructor.

What Causes NoSuchElementException

The NoSuchElementException can be thrown by various classes or interfaces in Java such as Iterator, Enumerator, Scanner or StringTokenizer.

If an element is requested using the accessor methods of these classes or interfaces, and the underlying data structure does not contain the element, the NoSuchElementException is thrown.

This can occur if the data structure is empty or if its next element is requested after reaching the end of the structure.

NoSuchElementException Example

Here is an example of a NoSuchElementException thrown when trying to access an element of an empty ArrayList using an accessor method of the Iterator interface:

public class NoSuchElementExceptionExample {
    public static void main(String args[]) {
        List<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> it = list.iterator();
        System.out.println(it.next());
    }
}

In the above example, an element of the ArrayList list is requested using the Iterator.next() accessor method. However, since list is empty, the element requested does not exist and the operation throws a NoSuchElementException:

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
    at NoSuchElementExceptionExample.main(NoSuchElementExceptionExample.java:9)

How to Fix NoSuchElementException

To fix the NoSuchElementException, it should be ensured that the underlying object contains more elements before using accessor methods that can throw the exception. The classes or interfaces that contain these accessor methods usually have a corresponding method to check whether the object contains more elements or not.

For example, the Iterator interface contains the hasNext() method, which should be called before calling Iterator.next() to ensure that the underlying object contains more elements. The Iterator.next() method should only be called if Iterator.hasNext() returns true.

In the earlier example, the exception can be resolved by implementing the above:

public class NoSuchElementExceptionExample {
    public static void main(String args[]) {
        List<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> it = list.iterator();

        while (it.hasNext()) {
            System.out.println(it.next());
        }

        System.out.println("Continuing execution...");
    }
}

Running the above code produces the correct output as expected:

Continuing execution...

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Many Java classes allow you to store objects in advanced ways. However, you may run into the Exception in Thread “Main” java.util.NoSuchElementException error when accessing them without care.

Keep reading to find out why the error happens and how you can prevent it.

Reproduce The Error

The java.util.NoSuchElementException error happens a lot when collections are used in Java. In particular, these two examples show how you may run into it when using StringTokenizer and Vector objects.

Example 1

import java.util.StringTokenizer;
public class NoSuchElementException {
    public static void example1() {
        String str = "Welcome to our website";
        StringTokenizer tokens = new StringTokenizer(str, " ");
        
        for(int i = 1; i < 6; ++i) {
            System.out.println(tokens.nextToken());
        }
    }
    public static void main(String[] args) {
        example1();
    }
}

In this example, we use the StringTokenizer class to split a string into tokens – one of the most popular applications of this class. However, after successfully printing out all the substrings, Java displays the error message related to java.util.NoSuchElementException.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
	at NoSuchElementException.example1(NoSuchElementException.java:8)
	at NoSuchElementException.main(NoSuchElementException.java:12)

In this example, we use Vector and Enumeration to access elements of a vector in Java.

Example 2

import java.util.Vector;
import java.util.Enumeration;
public class NoSuchElementException {
    public static void example2() {
        Vector<String> str = new Vector<>();
        str.add("Welcome");
        str.add("to");
        str.add("our");
        str.add("website");
        Enumeration<String> e = str.elements();
        for(int i = 1; i < 6; ++i) {
            System.out.println(e.nextElement());
        }
    }
    public static void main(String[] args) {
        example2();
    }
}

As with the first example, this program also shows the java.util.NoSuchElementException error message after printing every element of our vector.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
	at java.base/java.util.Vector$1.nextElement(Vector.java:344)
	at NoSuchElementException.example2(NoSuchElementException.java:27)
	at NoSuchElementException.main(NoSuchElementException.java:32)

java.util.NoSuchElementException

NoSuchElementException is a subclass of RuntimeException. Many accessor methods throw this exception when they want to tell you that the element you request doesn’t exist.

Common methods that produce this error are StringTokenizer.nextToken(), Enumeration.nextElement(), and Iterator.next().

In the first example, we use a for loop to control how many times the program should invoke the StringTokenizer.nextToken().

Particularly, the loop calls it five times, while the StringTokenizer instance only has four elements. That is why for the fifth time, Java prints out NoSuchElementException since there are no more elements for the StringTokenizer.nextToken() method to access.

The same thing happens to the second example with the Enumeration interface. Our string provides it with only four elements, but the for loop also calls the nextElement() five times. As a result, we also get the NoSuchElementException error.

This is a runtime exception, meaning the compiler won’t be able to detect any problems with your code. It is not until you run it with the Java Virtual Machine, that this exception will display.

Keep in mind that, like other exceptions in the superclass RuntimeException, there is no need to declare NoSuchElementException in your constructor or method’s throws clause. That is why these exceptions are called ‘unchecked’.

How To Fix The Error

Instead of using the for loop, you can use StringTokenizer.hasMoreTokens() and Enumeration.hasMoreElements() methods.

Example 1

while (tokens.hasMoreTokens()) {
    System.out.println(tokens.nextToken());
}

Example 2

for (Enumeration<String> e = str.elements(); e.hasMoreElements();)
    System.out.println(e.nextElement());

These methods check whether the StringTokenizer and Enumeration have more elements that you can access.

Summary

The Exception in Thread “Main” java.util.NoSuchElementException error occurs when you access elements that don’t exist. You should perform a check to avoid this problem.

Maybe you are interested:

  • ERROR : ‘compileJava’ task (current target is 11) and ‘compileKotlin’ task (current target is 1.8) jvm target compatibility should be set to the same Java version in Java
  • java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment
  • Error: Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context

Robert J. Charles

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python

Возможно, вам также будет интересно:

  • Java try catch все ошибки
  • Java swing сообщение об ошибке
  • Java sql sqlrecoverableexception ошибка ввода вывода socket read timed out
  • Java socket timeout exception ошибка
  • Java package does not exist intellij ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии