This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 5345 Thank you so much for your help.
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!
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. --Gary