Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

converting string to int - help!

 
Deyna Cegielski
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
im looking to write a method that reads a txt file which is storing weights in the form "11 lb 2 oz". reading the file is fine but i need to write a method fromString that extracts the 11 and the 2 from the string and stores them as int pounds and int ounces.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there's Integer.parseInt(), to convert a string to an integer.

An important thing to do in this type of problem is to find out exactly what format(s) the text lines will be in. Are pounds and ounces always given, or are ounces omitted if they are zero? Is there always exactly one space character between elements of the line, or does it vary?

Here are some possible approaches. Select according to your need/preference.

Use String.indexOf(), to find the "lb" and "oz" positions in the string. Use String.substring() to extract the numeric bits.

Use StringTokenizer to split into tokens. Use the first (pounds) and third (ounces) elements as the numeric bits.

Use Pattern and Matcher to identify the various bits of the string via a regular expression. Use "match groups" in the regular expression to pick out the numeric bits. This is a rather heavyweight solution, which is only likely to be necessary if your text lines have a quite variable format.

P.S. (European viewpoint) If you were using sensible metric units, you wouldn't have this problem!
 
Deyna Cegielski
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the weights will always be in the form "11 lbs 2 oz"
 
Deyna Cegielski
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think string tokenizer would be the best solution gna have to find my notes to remember how to use it unfortunetaly my hands are tied when it comes to the representation of the weights with regards t the metric system!
 
Petr Blahos
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:

P.S. (European viewpoint) If you were using sensible metric units, you wouldn't have this problem!


Metric units are more sensible alright, but not for this
reason.

5 tons 64 kg ;-)

BTW there are places in Europe where they use lbs and ozs.

P. (sorry for off-topic)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic