Solution – Java StringTokenizer java.util.NoSuchElementException

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.

Output

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.

Output

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.

Output

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.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *