我的意思是接收作为输入,例如:3和输出t,h,r,e。我正在考虑使用数组,但我必须存储从0到20的所有数字,然后是thenths(30,40等),直到100有更好的方法?
我正在使用Java,但目前还没有代码我正处于设计阶段。
答案 0 :(得分:0)
您可以使用地图。
public class NumberToWord {
private Map<Integer, String> map;
public NumberToWord() {
map = new HashMap<Integer, String>();
// populate all the strings for 0 - 20
// and 30, 40, ..., 100
map.put(0, "z,e,r,o");
map.put(1, "o,n,e");
map.put(2, "t,w,o");
map.put(3, "t,h,r,e,e");
map.put(4, "f,o,u,r");
map.put(5, "f,i,v,e");
map.put(6, "s,i,x");
map.put(7, "s,e,v,e,n");
map.put(8, "e,i,g,h,t");
map.put(9, "n,i,n,e");
map.put(10, "t,e,n");
map.put(11, "e,l,e,v,e,n");
map.put(12, "t,w,e,l,v,e");
map.put(13, "t,h,i,r,t,e,e,n");
map.put(14, "f,o,u,r,t,e,e,n");
map.put(15, "f,i,f,t,e,e,n");
map.put(16, "s,i,x,t,e,e,n");
map.put(17, "s,e,v,e,n,t,e,e,n");
map.put(18, "e,i,g,h,t,e,e,n");
map.put(19, "n,i,n,e,t,e,e,n");
map.put(20, "t,w,e,n,t,y");
map.put(30, "t,h,i,r,t,y");
map.put(40, "f,o,r,t,y");
map.put(50, "f,i,f,t,y");
map.put(60, "s,i,x,t,y");
map.put(70, "s,e,v,e,n,t,y");
map.put(80, "e,i,g,h,t,y");
map.put(90, "n,i,n,e,t,y");
map.put(100, "h,u,n,d,,r,e,d");
}
public String toWord(int number) {
if(number < 0 || number > 100) {
throw new IllegalArgumentException("number should 0 to 100");
}
if(number == 100 || number < 21) { //if the number is 100 or less than 21
return map.get(number); //just lookup and return
} else { //otherwise
int dig = number % 10;
String r = map.get(dig); //lookup for the last digit
dig = (number / 10) * 10; //and for the tens
r = map.get(dig) + "," + r; // and combine
return r;
}
}
public static void main(String... args) {
NumberToWord ntw = new NumberToWord();
System.out.println(0 + ": " + ntw.toWord(0));
System.out.println(1 + ": " + ntw.toWord(1));
System.out.println(11 + ": " + ntw.toWord(11));
System.out.println(20 + ": " + ntw.toWord(20));
System.out.println(29 + ": " + ntw.toWord(29));
System.out.println(99 + ": " + ntw.toWord(99));
System.out.println(100 + ": " + ntw.toWord(100));
System.out.println(75 + ": " + ntw.toWord(75));
}
}
输出:
0: z,e,r,o 1: o,n,e 11: e,l,e,v,e,n 20: t,w,e,n,t,y 29: t,w,e,n,t,y,n,i,n,e 99: n,i,n,e,t,y,n,i,n,e 100: h,u,n,d,,r,e,d 75: s,e,v,e,n,t,y,f,i,v,e
答案 1 :(得分:0)
如果我理解正确,您希望将整数映射到这些数字的英文单词。如果是这种情况,那么确实没有比你开始勾勒出来的方法更简单的方法。您的代码将需要存储没有规则的所有整数的单词,并捕获所有其他规则。
例如:对于0-19,您需要存储相应的单词。对于20,30,...,90,您需要存储这些单词。对于0到99之间的其余数字,您可以编写规则。 100,200,...,900的规则稍微容易一点,因为您只需要将相应的单位字放在“百”之前。等等。