将int值转换为不同的字符串值

时间:2013-01-26 19:30:13

标签: java string integer type-conversion

  

可能重复:
  How to convert number to words in java

我有一些Java代码接受参数,将它们转换为int值,对它们进行一些数学计算,然后将它们作为int值输出到10。我需要将这些输出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,但我无法弄明白。我甚至走在正确的道路上?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]);
}
相关问题