问题
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?
回答1:
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
回答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]);
}
来源:https://stackoverflow.com/questions/14540709/convert-int-value-to-a-different-string-value