how to check the next token is a integer or not .using StringTokenizer...if it is not an integer i have to skip the token and check the next token..

thanks in advance

8 Years
Discussion Span
Last Post by ~s.o.s~

You can use the method: Integer.parseInt

String s = "12";
try {
  int i = Integer.parseInt(s);

//do calculations here
} catch (NumberFormatException nfe) {

If s is not an integer then the method will throw an exception. So call the method I told you and if it is an int then continue doing whatever you want with the value. If it is not then the code will continue inside the catch.

You might want to search the internet for Exception handling tutorials


i have used String tokenizer to break the line into tokens..some of tokens iare not neccesarry for me..i need only integers so how can i check the token is an integer or not..??


I already told you how. Call the method I told you. It is not very hard to figure out what the argument should be. You said yourself what you want to check if it is an int or not


Well one word about the StringTokenizer class, this is what the javadocs have to say about it:-

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.


thnx Stephen..
as i am new at java...i dont know much...so its better to use java.util.regex class tahn string tokenizer..
and thnx for the link..


Use the split() method of the String class which returns a String array; loop over the array and apply the Integer.parseInt() method on each String token. If an exception is thrown; the string token isn't a valid integer.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.