File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes a program question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "a program question" Watch "a program question" New topic

a program question


Joined: Jun 19, 2000
Posts: 2
I'm having a trouble writing a program that will take, as String input of a English description of a number (0 - 9999), and print out the number in numeric format. For example,
if you input
Five thousand three hundred forty five
the program should print
Thank you so much for your help.
Paul Smiley
Ranch Hand

Joined: Jun 02, 2000
Posts: 244
I know of no way to do that except that you write your own parser - perhaps utilizing StringTokenizer - and go through each element and interpret it. But I think it's going to be messy because English isn't easily given to parsing, especially with semantic differences of the language. Think of things like 1500 being "fifteen hundred" or "one thousand five hundred", or numbers like 203 where the tens digit is understood to be zero. Good luck!
Gary Wilcox

Joined: Jun 20, 2000
Posts: 2
For a first whack at it I would try...
having name value pairs for the following 20 words. 1-18 being modifiers for the last 2.
"one" through "nine" (matched up to 1, 2, 3, 4, 5, 6, 7, 8, 9)
"ten" through "ninety" (matched up to 10, 20, 30, 40, 50, 60, 70, 80, 90)
"hundred" (matched to 100)
"thousand" (matched to 1000)
keep a running count and a stack as you parse the words in the input.
long myCount = 0;
Vector myVector = new Vector();
continue to parse the input words adding them to myVector until you reach the next modifier word (the first 18 constants). At that point multiply out everything in myVector adding the product to myCount. Then clear() the Vector and continue parsing your input.
for your example of...
Five thousand three hundred forty five
Initially "Five" would be added to myVector and then "thousand" would be added to myVector. Then "three" would be parsed and identified as a "modifier" so myVector would be processed, hence...
myCount += 5 * 1000; // myCount == 5000
the next 3 additions to myCount following the same logic would be...
myCount += 3 * 100; // myCount = 5300
myCount += 40; // myCount = 5340
myCount += 5; // myCount = 5345
Then System.out.println(myCount); would yield the desired "5345"
I hope this helped and wasn't too wordy.
I agree. Here's the link:
subject: a program question
It's not a secret anymore!