本文写了一个简单的金额转换程序,对刚刚接触的初学者来说,解决问题的思路可能不是那么清晰。题目:
如上,输入金额转换为大写。例如输入:2135 输出:零佰零拾零万贰仟壹佰叁拾伍元
import java.util.Scanner; public class StringDemo6 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); String reusult = moneyZhuanHuan(str); System.out.println(reusult); } public static String moneyZhuanHuan(String str) { if (str == null) { System.out.println("输入为空"); return ""; } if (str.length() > 7) { System.out.println("您输入的金额数量过多,无法转换"); return ""; } for (int i = 0; i < str.length(); i++) { if (str.charAt(i) < '0' || str.charAt(i) > '9') { System.out.println("输入的金额里面有不为数字的字符"); return ""; } } char[] c = {'零', '佰', '零', '拾', '零', '万', '零', '仟', '零', '佰', '零', '拾', '零', '元'}; str = moneyToChinese(str); int j = 0; for (int i = str.length() - 1; i >= 0; i--) { c[12 - j * 2] = str.charAt(i); j++; } String result = new String(c); return result; } public static String moneyToChinese(String str) { String result = ""; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case '1': result = result + "壹"; break; case '2': result = result + '贰'; break; case '3': result = result + '叁'; break; case '4': result = result + '肆'; break; case '5': result = result + '伍'; break; case '6': result = result + '陆'; break; case '7': result = result + '柒'; break; case '8': result = result + '捌'; break; case '9': result = result + '玖'; break; } } return result; } }