# new to java, converting words into numbers

• 04-21-2009, 01:56 PM
echo33
new to java, converting words into numbers
Hey all, my first post here

i have an assignment an i have to convert a user inputted string like:

"Some possible valid inputs are:

six thousand
two thousand, eight hundred
one thousand and one
nine thousand, nine hundred and nine
four hundred
five hundred and seven
three"

However, there will never be anything entered in the tens column, it will always be 0 (zero). Hence, numbers between 10 and 99 inclusive will not be used.

i am completely lost here and have started my code like this:

import java.util.*;
import java.io.*;

public class WordsToNumbers
{

public static void main (String[] args) throws IOException
{
String input;
String hundred;
String thousand;

Scanner keyboard = new Scanner(syste.in);

input = keyboard.nextLine();

}
}

any ideas?????:confused::confused: thanks heaps
• 04-21-2009, 08:20 PM
sirwiggles
First i would make sure all the string is in the same case, then split it into an array, broken up by spaces.
Then take out any commas, so what you are left with is an array with numbers and values.

Next cycle through the array to find "thousand" and "hundred".

If either are found, move back in the array by one element, this will be a number, pass this number through a function which converts it to a int, then times that int by either 1000, or 100.

A little complicated, I would start by creating a function which takes a number from 0-10 and returns the number written, for example if the number 5 if inputted, "five" would be returned.
• 04-22-2009, 01:00 AM
If this were my assignment, I would first do a 'tolower' on the inputs. Then I would strip out commas and 'ands', as they carry no information. Then I would split the input on whitespace to form tokens.

Next, I would push the the token into a stack, and then pop them off. I would create an array of Strings containing "zero", "one"..."nine", and I would compare each token popped off the stack to evry element in that array, adding the index to a running total if found.

If the token is not in that list, I would compare it to "hundred" and to "thousand", and if found, recursively call the number processing routine on the next stack entry, then multiply by 1000 or 100 as appropriate and add to the running sum.

If a token fails both of these sets of tests, spit out an error. Once the stack is empty, you have the answer.
• 04-22-2009, 05:12 AM
JohnnyR
have some constants set up as well to make it easier, e.g.

int ONE = 1;int TWO= 2;int THREE = 3;
int FOUR= 4;int FIVE= 5;int SIX= 6;
int SEVEN = 7;int EIGHT= 8;int NINE = 9;

Then have your hundreds etc set up
int HUNDRED = 00;
int THOUSAND = 000;
int TEN = 0;
• 04-22-2009, 09:52 AM
Xhile
no.
that wont work. what if they do two hundred and five. wouldnt it be 2005...