- import java.util.Scanner;
- public class convertNum {
- public static void main(String[] args) {
- System.out.println(convertNum());
- }
-
- /*private final static String[] STR_NUMBER = { "零", "壹", "贰", "叁", "肆", "伍",
- "陆", "柒", "捌", "玖" };*/
- private final static String[] STR_NUMBER = { "零", "一", "二", "三", "四", "五",
- "六", "七", "八", "九" };
- private final static String[] STR_UNIT = { "", "拾", "佰", "仟", "万", "拾",
- "佰", "仟", "亿", "拾", "佰", "仟" };
-
- /**
- * 转换方法
- * */
- public static String convertNum() {
- // 接收字符串
- String str = getNum();
- // 反转字符串
- str = new StringBuilder(str).reverse().toString();
-
- StringBuilder tempSB = new StringBuilder();
-
- for (int i = 0; i < str.length(); i++) {
- tempSB.append(STR_UNIT[i]);
- tempSB.append(STR_NUMBER[str.charAt(i) - '0']);
- }
- // 反转字符串
- str = tempSB.reverse().toString();
- // 替换字符串
- str = strReplace(str);
- // 返回转换后的字符串
- return str;
- }
- /**
- * 替换字符串
- * */
- private static String strReplace(String str) {
- // 替换字符串的字符
- str = strReplace(str, "零拾", "零");
- str = strReplace(str, "零佰", "零");
- str = strReplace(str, "零仟", "零");
- str = strReplace(str, "零万", "万");
- str = strReplace(str, "零亿", "亿");
- str = strReplace(str, "亿万", "亿");
- str = strReplace(str, "零零", "零");
- if (str.lastIndexOf("零") == str.length() - 1) {
- // 去掉字符串结尾的"零"
- str = str.substring(0, str.length() - 1);
- }
- return str;
- }
-
- /**
- * 替换指定字符
- * */
- private static String strReplace(String str, String oldStr, String newStr) {
- while (true) {
- // 判断字符串中是否包含指定字符
- if (str.indexOf(oldStr) == -1) {
- break;
- }
- // 替换字符串
- str = str.replaceAll(oldStr, newStr);
- }
- // 返回替换后的字符串
- return str;
- }
-
- /**
- * 返回输入的数字字符串
- * */
- private static String getNum() {
- Scanner sc = new Scanner(System.in);
-
- System.out.println("请输入一串数字:");
-
- while (true) {
- // 接收字符串
- String str = sc.nextLine();
- // 去掉所有空白字符
- str = str.replaceAll("\\s", "");
- // 判断字符串是否纯数字
- if (str.matches("\\d+")) {
- // 去掉字符串前面的0
- if(str.startsWith("0"))
- str = str.replaceFirst("[0]+", "");
- // 不超出转换范围则返回字符串
- if(str.length() <= 12)
- return str;
- }
-
- System.err.println("输入的不是纯数字,或超出转换范围(千亿以内),请重新输入:");
- }
- }
- }
复制代码 |