Question

I have my code here that would like to change Stringtokenizer to String because the information I get is in sentence and I would like to cut it down to certain part.

StringTokenizer numberOfPost_string = new StringTokenizer( numberOfPost_text , delimiters );

System.out.println( numberOfPost_string.nextToken() );

int numberOfPost = Integer.parseInt(numberOfPost_string);

The problem I encounter is on the line int numberOfPost = Integer.parseInt(numberOfPost_string); where it gives me error.

Or is there other way for me to cut down sentence and convert it to integer?

Was it helpful?

Solution

You probably want to use the return value of nextToken:

StringTokenizer numberOfPost_string = new StringTokenizer( numberOfPost_text , delimiters );
int numberOfPost = Integer.parseInt(numberOfPost_string.nextToken());

You can also do it with split: (although this is probably slightly less efficient)

int numberOfPost = Integer.parseInt(numberOfPost_text.split(delimiters)[0]);

Keep in mind that split takes a regular expression String, thus to specify multiple options for characters, you will need to surround them by []. To specify ;, , or ::

String delimiters = "[;,:]";

OTHER TIPS

To convert the tokens to string

String x = "";
StringTokenizer in = new StringTokenizer(str, ",;");
while(in.hasMoreTokens()) {
    x = x + in.nextToken().toString();
}
System.out.print(x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top