java.util.StringTokenizer.hasMoreTokens()
Description
Depending on the circumstances and what you want to achieve, this method will achieve the same result as the combination of countTokens() and nextToken(). Basically if we don’t need to concern ourselves on the count of tokens, the hasMoreTokens is a good way to get the tokens.
Method Syntax
public boolean hasMoreTokens()
Method Returns
The hasMoreTokens() method returns true if and only if there is at least one token in the string after the current position; false otherwise.
Compatibility
Requires Java 1.0 and up
Java STringTokenizer hasMoreTokens() Example
Below is a java code demonstrates the use of hasMoreTokens() method of StringTokenizer class. The example presented might be simple however it shows the behaviour of the hasMoreTokens() method.
package com.javatutorialhq.java.examples; import java.util.StringTokenizer; /* * This example source code demonstrates the use of * hasMoreTokens() method of StringTokenizer class. * */ public class StringTokenizerHasMoreTokensExample { public static void main(String[] args) { //declare a new String with tokens delimited by | String input = "Beth|Ryan|Grace|Travis|Vince"; /* * initialize our StringTokenizer using input * as source String and | as the delimiter */ StringTokenizer st = new StringTokenizer(input,"|"); // print all tokens while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } } }
The above java example source code demonstrates the use of hasMoreTokens() method of StringTokenizer class. Basically we just declared a new String object with tokens delimited by “|”. We make use of one of the constructor of StringTokenizer class that accepts the String input and delimiter. Since the hasMoreTokens() check if there are still available tokens on the buffer, we can use this as a check on our while loop. The while loop will iterate until there are tokens available. And we used the nextToken() to get the current token and advance to the next one. The combination of this two are the fundamentals in using the StringTokenizer.