【问题标题】:Convert int Value to a Different String Value [duplicate]将 int 值转换为不同的字符串值 [重复]
【发布时间】:2013-01-27 03:43:39
【问题描述】:

可能重复:
How to convert number to words in 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 = 二等)我知道我必须声明值 8 是字符串 8,但我无法弄清楚。我是否走上了正确的道路?

【问题讨论】:

  • 我会使用包含字符串“one”、“two”的String[]...而不是使用int'b'作为索引从数组中获取想要的字符串。
  • 考虑查看 Oracle Java 教程中的 this chapter。
  • 要么使用字符串数组,要么只使用静态映射来进行基于 int 的查找。

标签: java string integer type-conversion


【解决方案1】:

这是一种方法:

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

【讨论】:

  • 你的回答很有道理,但我只有大约三周的编程时间。有人评论说使用 switch 语句似乎更容易实现。不过感谢您的帮助!
【解决方案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-11-04
    • 2019-08-30
    • 1970-01-01
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2014-09-08
    相关资源
    最近更新 更多