1

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?

Poh Sun
  • 75
  • 1
  • 2
  • 11
  • you need to post up the contents of numberOfPost_text and delimiters – tom Oct 24 '13 at 17:02
  • What I get from numberOfPost_text is "1,221 ( 0.9 posts per day / 0.00% of total forum posts )". What I want is the 1,221 value from the string. My deliminators is the whitespace – Poh Sun Oct 24 '13 at 17:27
  • use regular expressions for that, not string tokenizer – tom Oct 24 '13 at 18:18

2 Answers2

2

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 = "[;,:]";
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • There seems to be problem at `int numberOfPost = Integer.parseInt(numberOfPost_string.nextToken());` I get errors on that line. Could you please help me check? Sorry, I'm new to Java. – Poh Sun Oct 24 '13 at 16:36
  • Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1,221" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at fyp.draft.pkg1.Design.jButton2ActionPerformed(Design.java:161) and many more – Poh Sun Oct 24 '13 at 17:20
  • Which says exactly what it means. 1,221 is not a valid int. 1221 is. – tom Oct 24 '13 at 18:19
  • @PohSun `1,221` cannot get parsed by `parseInt`. See [this question](http://stackoverflow.com/a/11973442/1711796). – Bernhard Barker Oct 24 '13 at 18:27
  • @Dukeling. Got it. Sorry. Wasn't aware of it. My errors has been fixed. Sorry and thank you for your time. – Poh Sun Oct 24 '13 at 19:31
0

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);
pajaja
  • 2,164
  • 4
  • 25
  • 33