0

Possible Duplicate:
How to convert number to words in java

I have some Java code that takes arguments, converts them to int values, does a little bit of math on them and then outputs them as int values up to 10. I need to take these output int values and convert them to another string.

For example:

int a = 6;
int b = a + 2;
System.out.print(b);

That will print the value 8. I know that I can convert int b to a string:

int a = 6;
int b = a + 2;
String b1 = Integer.toString(b);
System.out.print(b1);

This will turn my int b into String b1, but the output will still be 8. Since my values will only be a number 1 through 10 inclusive, how do I convert these values to their string counterpart (1 = one, 2 = two, etc.) I know that I'll have to declare that the value 8 is String eight, but I cannot figure it out. Am I even going down the right path?

Community
  • 1
  • 1
rice2007
  • 115
  • 12
  • I would use a `String[]` containing zthe Strings "one", "two" ... And than use the `int` 'b' as index to get the wanted String from the array. – MrSmith42 Jan 26 '13 at 19:33
  • Consider looking at [this chapter](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) in the Oracle Java tutorial. – jlordo Jan 26 '13 at 19:33
  • 1
    Either use the string array or just have a static map to do the int based lookup. – Scorpion Jan 26 '13 at 19:36

2 Answers2

4

Here is one way to do it:

String[] asString = new String[] { "zero", "one", "two" };    
int num = 1;
String oneAsString = asString[num]; // equals "one"

Or better put:

public class NumberConverter {
  private static final String[] AS_STRING = new String[] { "zero", "one", "two" };    

  public static String getTextualRepresentation(int n) {
    if (n>=AS_STRING.length || n<0) {
       throw new IllegalArgumentException("That number is not yet handled");
    }
    return AS_STRING[n];
  }
}

--

Edit see also: How to convert number to words in java

Community
  • 1
  • 1
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
  • Your answer makes sense, but I've only had about three weeks of programming. Someone commented on using switch statements which seems a bit easier to implement. Thanks for the help though! – rice2007 Jan 26 '13 at 21:36
2

There are a few different ways of doing it. My personal preference is something like.

String text[] = {"zero","one","two","three","four","five","six","seven",
    "eight","nine","ten"};

void printValue(int val, int off)
{
   //Verify the values are in range do whatever else
   System.out.print(text[val+off]);
}
twain249
  • 5,666
  • 1
  • 21
  • 26