在(0~9999)范围内将数字转成汉字形式

该文章介绍了如何使用Java编写一个名为`numberToChinese`的类,用于将0-9999范围内的整数转换为对应的中文数字表示,包括千位、百位、十位和个位的组合形式。
摘要由CSDN通过智能技术生成
public class numberToChinese {
    private static final String[] UNITS = { "一", "二", "三", "四", "五", "六", "七", "八", "九","十"};
    private static final String[] UNITSK = {"十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九"};
    private static final String[] TEENS = {"一十", "二十", "三十", "四十", "五十", "六十", "七十", "八十", "九十"};

    public String numberToChinese(int num) {
        if (num<10&&num>0){
            return UNITS[num-1];
        }
        if (num == 0) {
            return "零";
        }
        if (num>=10&&num<=19){
            int result=num%10;
            return UNITSK[result];
        }

        StringBuilder result = new StringBuilder();
        if (num >= 10000) {
            throw new IllegalArgumentException("超出范围(只支持0-9999)");
        }

        int thousands = num / 1000;
        if (thousands > 0) {
            if (thousands==2){
                result.append("两千");
            }else {
                result.append(UNITS[thousands-1]).append("千");
            }
            num %= 1000;

            // 处理千位之后的零,如2005应为两千零五,而非两千五百
            if (num != 0) {
                result.append(num < 100 ? "零" : "");
            }
        }

        int hundreds = num / 100;
        if (hundreds > 0) {
            if (hundreds==2){
                result.append("两百");
            }else {
                result.append(UNITS[hundreds - 1]).append("百");
            }
            num %= 100;
        }

        Boolean flag=false;
        if (num >= 10) {
            int tensIndex = num / 10 - 1; // 转换为TEENS数组的索引
            result.append(TEENS[tensIndex]);
            num %= 10;
            flag=true;
        }

        if (num > 0) {
            if (flag){
                result.append(UNITS[num-1]);
            }else {
                result.append("零").append(UNITS[num-1]);
            }
        }

        // 处理连续的零和一的情况
        String strResult = result.toString();
        return strResult.isEmpty() ? "零" : simplifyZeros(strResult);

    }

    public static void main(String[] args) {
        numberToChinese number = new numberToChinese();
        System.out.println(number.numberToChinese(1001));
    }

    public static String simplifyZeros(String number) {
        return number.replaceAll("(零)+", "零");
    }
}

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值