• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how to add numbers in string

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello!

I am a newbie to Java. I have a string e.g "12 03". I need to add the two numbers present in

this string (sum = 15). Can someone please guide me how to do this.


Thanks in advance,
Sanjul
 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could I know how your string is formed in that fashion ("12 3")?

Do some reading on String Tokenizer.

I am sure that you will find out how do to it yourself.

Hope this helps.

Follow this link
http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
[ October 22, 2004: Message edited by: rahul V kumar ]
 
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use stringtokenizer to break up the token using " " as the delimiter.
Once you have done that, use Integer.parseInt to convert each of the strings to int and then add them. Easy.
 
Sanjul Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a ton!


I need to change string "7777" to integer 7777, and integer 15 to string "15".

I would appreciate if you can help.

Thanks in advance,
Sanjul
 
rahul V kumar
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should get your answers here
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

String to int
int i = Integer.parseInt("7777");

you can have it in a try catch block or check to make sure that the string is indeed a valid number.
[ October 22, 2004: Message edited by: rahul V kumar ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic