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';
}
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();
}
}
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();
}
}
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:
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();
}
}
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();
}
}
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:
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';
}
- NoSuchElementException While Using Iterator in Java
- NoSuchElementException While Using Enumeration in Java
- NoSuchElementException While Using StringTokenizer in Java
- NoSuchElementException While Using Scanner Class 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.
- 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.
- 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:
java.util.NoSuchElementException
is a RuntimeException or say an UncheckedException and therefore it does not need to be declared in a constructor’s or a method’s throw block.
Table of Contents
- Scenario 1: In case of Enumeration
- Solution
- Scenario 2: In case of Iterator
- Solution
- Scenario 3: In case of StringTokenizer
- Solution
java.util.NoSuchElementException
is usually thrown when we try to access some element which is not present or reserved for the underlying data structure in the heap, and, thrown by the different classes, which have method to fetch the next element or next tokens, like Iterator :: next(), Enumeration :: nextElement() , StringTokenizer :: nextToken().
Example
When we are iterating over hashmap without implementing the condition to check if there is any element or not, this exception is raised or thrown by Java, now this is the reason we use hasNext() before calling next() on Iterator.
There can be multiple scenarios for java.util.NoSuchElementException. Let’s understand each with the help of examples.
Scenario 1: In case of Enumeration
In Enumeration, if we call the method nextElement() and there is no element present in enumeration then this exception is raised, refer the code below.
Syntax :
package org.arpit.java2blog; import java.util.*; class Main { public static void main(String args[]) { Hashtable hmap = new Hashtable(); Enumeration enumer = hmap.elements(); enumer.nextElement(); // java.util.NoSuchElementExcepiton // because the enumeration is empty } } |
Output:
Exception in thread “main” java.util.NoSuchElementException
at java.util.Collections$EmptyEnumeration.nextElement(Collections.j ava:4270)
at Main.main(Main.java:7)
Solution
By using a condition to check if it really have elements by calling method hasMoreElements()
.
Code:
package org.arpit.java2blog; import java.util.*; class Main { public static void main(String args[]) { Hashtable hmap = new Hashtable(); Enumeration enumer = hmap.elements(); if (enumer.hasMoreElements()) { //java.util.NoSuchElementExcepiton handled by checking enumer.nextElement(); } } } |
Above program will run perfectly fine with no exceptions.
Scenario 2: In case of Iterator
In iterator, if we call the method next() and there is no element present in iterator then this exception is raised, refer the code below.
package org.arpit.java2blog; import java.util.*; class Main { public static void main(String args[]) { HashMap hMap = new HashMap(); Iterator itr = hMap.keySet().iterator(); itr.next(); //java.util.NoSuchElementException here because iterator is //empty } } |
Output:
Exception in thread “main” java.util.NoSuchElementException at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1447) at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
at Main.main(Main.java:6)
Solution
By implementing a condition to check if there is any next element by calling method hasNext().
Code:
package org.arpit.java2blog; import java.util.*; class Main { public static void main(String args[]) { HashMap hMap = new HashMap(); Iterator itr = hMap.keySet().iterator(); if (itr.hasNext()) itr.next(); // java.util.NoSuchElementExcepiton handled } } |
Now, this runs without throwing the given Exception.
Scenario 3: In case of StringTokenizer
In StringTokenizer, if we call the method nextElement() or nextToken() and there is no element or token present then this exception is raised, refer the code below.
package org.arpit.java2blog; import java.util.StringTokenizer; class Main { public static void main(String args[]) { StringTokenizer token = new StringTokenizer(«», «:»); System.out.println(token.nextToken()); } } |
Output:
Exception in thread “main” java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken (StringTokenizer.java:349)
at Main.main (Main.java:5)
Solution
By using Stringtokenizer’s hasMoreTokens() or hashMoreElements()
before proceding to call nextToken() or nextElement().
Code:
package org.arpit.java2blog; import java.util.StringTokenizer; class Main { public static void main(String args[]) { StringTokenizer token = new StringTokenizer(«», «:»); while (token.hasMoreTokens()) // Exception Handled System.out.println(token.nextToken()); } } |
Above program will run perfectly fine with no exceptions.
In this tutorial, we will discuss about the java.util.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 java.util.nosuchelementexception existed since the first version of Java.
1. 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.
2. The java.util.nosuchelementexception Exception in Java
The NoSuchElementException
can be thrown by the following methods:
Enumeration::nextElement()
NamingEnumeration::next()
StringTokenizer::nextElement()
Iterator::next()
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 java.util.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)
3. How to deal with the java.util.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()); } }
4. Download the Eclipse Project
This was a tutorial about the NoSuchElementException
in Java.
Last updated on Dec. 09th, 2021
In this tutorial, Learn how to fix java.util.NoSuchElementException: No value present error in java application.
This error java.util.NoSuchElementException: No value present
thrown when there is no element found in Optional
object with Stream API in java8.
Let’s create an array and initialize it with string values. You can check how to create and initialize an array in a single line
Let’s see a simple example to check if a string exists in an array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> srs = new ArrayList<>(Arrays.asList("One", "two", "three"));
String str=srs.stream().filter(e->e.equals("ten")).findFirst().get();
}
}
It throws an error Exception in thread “main” java.util.NoSuchElementException: No value present
Exception in thread "main" java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at Test.main(Test.java:8)
Let’s understand the above code.
- Iterated an array using stream API in java8, Stream is another way to iterate the enumerated object to improve performance
- It returns the Stream object using the stream() method
- Calling filter method on stream which matched with a given predicate for each element and returns matched values with stream
- Calling the first element using findFirst from the matched stream and returns Optional class
- if
optional
Object is empty,get
method returnno value present
error
i.e Optional.get() method gives java.util.NoSuchElementException when Optional object is empty
Here is a get method implemented in java8
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
There are multiple ways we can fix to check for the optional object is empty or not.
Let’s see some other simple examples to reproduce and solution for this error
Optional<Integer> number1 = Optional.of(123);
Optional<Integer> number2 = Optional.empty();
System.out.println(number1.get()); // 123
System.out.println(number2.get()); // Exception in thread "main" java.util.NoSuchElementException: No value present
One way,
We can check Optional empty or not using isPresent() method in Optional class
if (number2.isPresent()){
System.out.println(number2.get());
}else{
System.out.println("number2 is an empty");
}
isPresent()
method returns true
if value exists, else return false
.
Thus, we can avoid an error.
Another way using the orElse
method
The orElse
method returns the default value assigned with an argument if optional is empty.
otherwise, the returns value is present in the Optional class.
Optional<Integer> number1 = Optional.of(123);
System.out.println(number1.orElse(0)); // 123
Optional<Integer> number2 = Optional.empty();
System.out.println(number2.orElse(0));
Finally, you can use the orElseThrow method.
Sometimes we want to throw an error if Optional is empty, It is handy and helpful.
Optional<Integer> number1 = Optional.of(123);
System.out.println(number1.orElse(0)); // 123
Optional<Integer> number2 = Optional.empty();
System.out.println(number2.orElseThrow(Exception::new));
We can use either orElse with the default value orElseThrow method.
How to fix NoSuchElement error in java8 streams
Here is a complete example to avoid errors in the java8 stream.
It usually occurs during the streaming process with map
, filter
etc. methods.
We have to use orElse
returns assigned default value else the return value exists in the Optional class.
import java.util.List;
import java.util.Optional;
public class Test {
public static void main(String[] args) throws Exception{
List<String> srs = new ArrayList<>(Arrays.asList("one", "two", "three"));
String result=srs.stream().filter(e->e.equals("ten")).findFirst().orElse("");
System.out.println(result);
String result1=srs.stream().filter(e->e.equals("one")).findFirst().orElse("");
System.out.println(result1);
}
}
Conclusion
You learned multiple ways to fix java.util.NoSuchElementException: No value present
error in java8 streams.