Convert int Value to a Different String Value [duplicate]

纵饮孤独 提交于 2020-01-07 08:33:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!