-1

可能重复:
如何在java中将数字转换为单词

我有一些 Java 代码,它们接受参数,将它们转换为 int 值,对它们进行一些数学运算,然后将它们输出为最大为 10 的 int 值。我需要获取这些输出 int 值并将它们转换为另一个字符串。

例如:

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

这将打印值 8。我知道我可以将 int b 转换为字符串:

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

这会将我的 int b 转换为 String b1,但输出仍然是 8。由于我的值将只是 1 到 10 的数字,我如何将这些值转换为对应的字符串(1 = 1,2 = 2,等)我知道我必须声明值 8 是字符串 8,但我无法弄清楚。我什至走在正确的道路上吗?

4

2 回答 2

3

这是一种方法:

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

或者更好的说法:

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];
  }
}

--

编辑参见:How to convert number to words in java

于 2013-01-26T19:35:50.160 回答
2

有几种不同的方法可以做到这一点。我个人的喜好是这样的。

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]);
}
于 2013-01-26T19:36:28.073 回答