Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# String question

Lydia Su
Greenhorn
Posts: 13
i have a question....how do you convert a user-input string into separate strings? say like if i enter 537, the program breaks it into three separate strings...and how to make these separate strings output "Five hundred and thirty seven."???

karl koch
Ranch Hand
Posts: 388
hi,
you can split it using the Strings charAt() or substring() methods.
then convert it to int[] using the Integer.parseInt() in a method in a loop.
put "", "one, "two", "three",... "ten", "twenty",..... in a 2-dimensional String array where the first row stands for the string representation of 0 -9, second for 10 - 90, third for 100 to 900 and so on.
from the int[] you can get 2 params: the index and the value at this index-> the index = row in the string array and the value = collumn in the string array.
does this sound weard ? should work.
karl

Bob Graffagnino
Ranch Hand
Posts: 81
If there is a common delimiting character you could use the StringTokenizer class. It can be especially useful when the exact position of the next sub-string is not known.

John Lee
Ranch Hand
Posts: 2545
You first need to break '537' to '5', '3', and '7'.
Then use case ststement to convert them to 'five hundred', 'thirty', and 'seven'.

Layne Lund
Ranch Hand
Posts: 3061
I would use Integer.parseInt() to convert the whole string to an int, first. Then you can use the modulus (%) and divide (/) operators to strip digits from the int. From there, either use an array of String or a switch statement to print out the tokens. I think I like the array idea best.
Keep coding!
Layne

John Lee
Ranch Hand
Posts: 2545
That is a good idea too.
I think the most time consuming part is to convert number to name, such as: one, two, ten, two hundred.
Our methods are different in term of how to get the number at each digit. But to convert them, I probably have to use a swith statement with 10 cases.
I am wondering if there is better way to do this?

Barry Gaunt
Ranch Hand
Posts: 7729
Yup, CattleDrive Java 4a/4b 200\$ a ride.