Solution – Java StringTokenizer java.util.NoSuchElementException example shows how to solve NoSuchElementException while using the StringTokenizer object.
How to solve java.util.NoSuchElementException while using the StringTokenizer object?
The StringTokenizer class in Java creates string tokens from the provided content and the delimiter values. Once these tokens are generated we can access these tokens using the nextToken
or nextElement
methods.
See below-given code example that shows how it works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerNoSuchElementException { public static void main(String[] args) { String strContent = "Hello world"; StringTokenizer st = new StringTokenizer( strContent, " "); System.out.println(st.nextToken()); } } |
Output
1 |
Hello |
The nextToken
method advances internal position to the next delimiter found in the string data. So when we call the nextToken
method again, it returns the next token in the content.
The NoSuchElementException exception is thrown by Java when we call the nextToken
method but there are no more tokens to be fetched from the tokenizer. See the below example to understand it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.javacodeexamples.stringtokenizerexamples; import java.util.StringTokenizer; public class StringTokenizerNoSuchElementException { public static void main(String[] args) { String strContent = "Hello"; StringTokenizer st = new StringTokenizer( strContent, " "); System.out.println(st.nextToken()); System.out.println(st.nextToken()); } } |
Output
1 2 3 4 |
Hello Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source) at com.javacodeexamples.stringtokenizerexamples.StringTokenizerNoSuchElementException.main(StringTokenizerNoSuchElementException.java:14) |
In the above example, I called the nextToken
method two times but there was only one token in the string content.
Solution:
The StringTokenizer class provides the hasMoreTokens
method just for that purpose. It returns true if there are more tokens available to fetch, false otherwise.
Always call this method to check for more tokens before calling the nextToken
method as shown in the below example.
1 2 3 4 5 6 7 |
String strContent = "Hello"; StringTokenizer st = new StringTokenizer( strContent, " "); while( st.hasMoreTokens() ) { System.out.println( st.nextToken() ); } |
Output
1 |
Hello |
Never call the nextToken
method before checking the availability of more tokens to make sure that this exception is never thrown by the code.
If you want to learn more about the tokenizer, please visit the Java StringTokenizer tutorial.
Please let me know your views in the comments section below.