문제

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?

도움이 되었습니까?

해결책

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 = "[;,:]";

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top