递归调用,枚举所有情况
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static String[] wei = new String[] {"拾", "佰", "仟"};
public static StringBuffer result = new StringBuffer();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String input = in.nextLine();
System.out.println("人民币" + changede(input));
}
}
public static String changede(String input) {
Map<Integer, String> map = new HashMap<>();
map.put(0, "零"); map.put(1, "壹"); map.put(2, "贰"); map.put(3, "叁");
map.put(4, "肆"); map.put(5, "伍"); map.put(6, "陆"); map.put(7, "柒");
map.put(8, "捌"); map.put(9, "玖"); map.put(10, "拾");
String[] str = input.split("\\.");
int number = Integer.parseInt(str[0]);
StringBuffer sb = new StringBuffer();
zhuanhuan(number, sb, map);
if (result.length() > 0) result.append("元");
int xiaoshu = Integer.parseInt(str[1]);
if (xiaoshu == 0) return result.append("整").toString();
int shiwei = xiaoshu / 10;
int gewei = xiaoshu % 10;
if (shiwei == 0 && gewei != 0) return result.append(map.get(gewei)).append("分").toString();
if (shiwei != 0 && gewei == 0) return result.append(map.get(shiwei)).append("角").toString();
return result.append(map.get(shiwei)).append("角").append(map.get(gewei)).append("分").toString();
}
public static void zhuanhuan(int number, StringBuffer sb, Map<Integer, String> map) {
if (number == 0) {
result = sb;
return;
}
int next = number / 10000;
int current = number % 10000;
int gewei = current % 10;
int shiwei = (current / 10) % 10;
int baiwei = (current / 100) % 10;
int qianwei = (current / 1000) % 10;
StringBuffer temp = new StringBuffer();
if (number >= 10000) temp.append("万");
if (number >= 10000 && qianwei == 0) temp.append("零");
if (qianwei != 0) temp.append(map.get(qianwei)).append("仟");
if (qianwei != 0 && baiwei == 0 && shiwei == 0 && gewei == 0) {
StringBuffer nextSb = temp.append(sb);
zhuanhuan(next, nextSb, map);
return;
}
if (baiwei == 0 && qianwei != 0) temp.append("零");
if (baiwei != 0) temp.append(map.get(baiwei)).append("佰");
if (baiwei != 0 && shiwei == 0 && gewei == 0) {
StringBuffer nextSb = temp.append(sb);
zhuanhuan(next, nextSb, map);
return;
}
if (shiwei == 0 && baiwei != 0) temp.append("零");
if (shiwei != 0) {
if (shiwei != 1) {
temp.append(map.get(shiwei)).append("拾");
} else {
temp.append("拾");
}
}
if (gewei != 0) temp.append(map.get(gewei));
StringBuffer nextSb = temp.append(sb);
zhuanhuan(next, nextSb, map);
}
}