dcsimg
How to get string to integer convrsion in a tokenized string with delimiters which some token need to be converted to string.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   jeff_mani
Posted On:   Sunday, January 11, 2009 12:52 PM

I was writing a program to read an input file and write it to the output file in which words in the input file have comma as delimiters. Some of the tokens with delimiters have to be converted to integers when is written to the output file. There was no problem without delimiter. But there was an error message in running the program when delimiter is used. So I wrote a small code to test the conversion of tokens with delimiters into integers and there was the same problem. I put the small code here to see if any one can HELP ME to figure this problem. The program works if i remove commas. Thanks, Jeff import java.util.*; public class String_Tokenized { public static void main(String [   More>>

I was writing a program to read an input file and write it to the output file in which words in the input file have comma as delimiters. Some of the tokens with delimiters have to be converted to integers when is written to the output file. There was no problem without delimiter. But there was an error message in running the program when delimiter is used. So I wrote a small code to test the conversion of tokens with delimiters into integers and there was the same problem. I put the small code here to see if any one can HELP ME to figure this problem. The program works if i remove commas.

Thanks,
Jeff



import java.util.*;


public class String_Tokenized {


public static void main(String [] args) {


String Demo = "This, is, string, 220, 320";


StringTokenizer Tok = new StringTokenizer
(Demo, ",");



String first = Tok.nextToken();

String second = Tok.nextToken();

String third = Tok.nextToken();


int num1 = Integer.parseInt(Tok.nextToken());

int num2 = Integer.parseInt(Tok.nextToken());



System.out.println(first + " " + second + " "+third);

System.out.println(num1 +" "+num2);

}

}
   <<Less

Re: How to get string to integer convrsion in a tokenized string with delimiters which some token need to be converted to string.

Posted By:   Tim_Frith  
Posted On:   Monday, January 12, 2009 02:49 PM

The problem is the spaces after the commas. They are included in the token. So you are trying to parse " 220" to an int and not "220".

Change
int num1 = Integer.parseInt(Tok.nextToken());

to
int num1 = Integer.parseInt(Tok.nextToken().trim());
About | Sitemap | Contact