这题目不算太难,就是单独敲出来挺费时间
[Java] 纯文本查看 复制代码 public class Test1 {
public static void main(String[] args) {
//测试如下
System.out.println(changeNum("1234"));
System.out.println(changeNum("12340123"));
System.out.println(changeNum("90123410011001"));
System.out.println(changeNum("101000001010"));
System.out.println(changeNum("90123400001010"));
//测试异常
// System.out.println(changeNum("90123400001010A"));
}
//完成金额转换方法的定义
public static String changeNum(String str){
if(str==null || !str.matches("[0-9]+")){
throw new RuntimeException("字符串为空或含有非阿拉伯数字");
}
String[] num = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
String[] arr = {"拾","佰","仟","萬","亿"};
StringBuilder sb = new StringBuilder();
//处理万位以下数目
if(str.length()<5){
for(int i=str.length() - 1; i >=0;i--){
char c = str.charAt(i);
int k = Integer.parseInt(c+"");
if(k==0 || i == str.length() - 1){
if( k==0 && i==str.length() -1)
;
else
sb.insert(0, num[k]);
}else{
sb.insert(0, num[k]+arr[str.length() - i -2]);
}
}
}
else{
//处理亿位以下数目,通过递归 分别处理 万位 及万位以下数据
if(str.length() < 9){
int k = str.length() - 4;
String f = changeNum(str.substring(0,k));
if(f.equals("零")||f.equals("零圆整"))
sb.append(f+changeNum(str.substring(k,str.length())));
else
sb.append(f+arr[3]+changeNum(str.substring(k,str.length())));
}else{
if(str.length() > 8){
int k = str.length() - 8;
sb.append(changeNum(str.substring(0,k))+arr[4]+changeNum(str.substring(k,str.length())));
}
}
}
//处理字符串中的多零情况,并返回
return sb.toString().replaceAll("[零]+", "零").replaceAll("[圆整]", "")+"圆整";
}
}
|