这个程序的难点主要在与“零”的问题是怎么解决的,主要有以下几种情况:
1、10:如何只显示“壹拾”
2、10010:如何将中间多个0只显示成一个”零“
3、1001000:此时应该输出”壹佰萬壹仟“,也就是说前面的两个0都没有显示出来
package programmer;
import java.util.Scanner;
/*
* 实现将"123456789"转化为"壹亿贰仟叄佰肆拾伍萬陆仟柒佰捌拾玖"
*/
public class NumbertoCnModify {
public String toCapital(String str) {
int n = Integer.valueOf(str);
switch (n) {
case 0:
return "零";
case 1:
return "壹";
case 2:
return "贰";
case 3:
return "叄";
case 4:
return "肆";
case 5:
return "伍";
case 6:
return "陆";
case 7:
return "柒";
case 8:
return "捌";
case 9:
return "玖";
}
return null;
}
public String numberToCn(String str) {
String result = "";
int tag = 0, i, j;
for (i = str.length() - 1, j = 0; i >= 0; i--, j++) {
String tmp = String.valueOf(str.charAt(j));
if (tmp.equals("0")) {
if (tag == 0) {
if (str.length() - j >= 9) { // 这里是假设过亿的情况
if (str.charAt(str.length() - 9) != '0')
result += toCapital(tmp);
} else if (str.length() - j >= 5) { // 这里是假设处在萬和亿之间的情况
if (str.charAt(str.length() - 5) != '0')
result += toCapital(tmp);
} else if (str.length() - j > 1 // 这是是假设在萬一下且最后一位不为零的情况
&& str.charAt(str.length() - 1) != '0') {
result += toCapital(tmp);
}
tag = 1;
}
if (str.length() - j == 8)
result += toCapital(tmp);
if (str.length() - j == 4)
result += toCapital(tmp);
if (str.length() - j == 9)
result += "亿";
if (str.length() - j == 5)
result += "萬";
} else {
result += toCapital(tmp);
switch (i) {
case 1:
case 5:
case 9:
result += "拾";
break;
case 4:
result += "萬";
break;
case 2:
case 6:
case 10:
result += "佰";
break;
case 3:
case 7:
case 11:
result += "仟";
break;
case 8:
result += "亿";
break;
}
tag = 0;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String numberStr = sc.nextLine();
System.out.println(new NumbertoCnModify().numberToCn(numberStr));
}
}