用java写一个金额转换(数字转中文)

本文写了一个简单的金额转换程序,对刚刚接触的初学者来说,解决问题的思路可能不是那么清晰。题目:

如上,输入金额转换为大写。例如输入: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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值