当我们去查看支票上的数字或着账单上的数字时,会发现它们都是用中文来表达数字的,那么此时的需求就是将用户输入的阿拉伯数字转换为中文表达的形式(不得超过9999999),而且如果在该单位上没有数值的统一写成零,样品如下:
666
转化后如下
零佰零拾零万零仟陆佰陆拾陆元
具体实现如下:
1:可以将传入的阿拉伯数字转为对应的中文表达
public static String moneyChange(int num){
String[]arr = new String[]{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
return arr[num];
}
2.将转换后的数据进行拼接并加以单位修饰
public static String Css(String result){
String newResult = "";
String[]arr = new String[]{"元","拾","佰","仟","万","拾","佰"};
int j = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
//判断是否在该位上有数据,没有则补零
if(i == arr.length - result.length())
break;
newResult = newResult + '零' + arr[j--];
}
for (int i = 0; i < result.length(); i++) {
newResult = newResult + result.charAt(i) + arr[j--];
}
return newResult;
}
完整代码如下:
import java.util.Scanner;
public class changeMoney {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("请输入你需要转换的金额");
int num = sc.nextInt();
int ge = 0;
String result = "";
if(num>=0 && num<=9999999){
while(num>0){
ge = num % 10;
num /= 10;
result = moneyChange(ge) + result;
}
result = Css(result);
System.out.println(result);
}
}
public static String moneyChange(int num){
String[]arr = new String[]{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
return arr[num];
}
public static String Css(String result){
String newResult = "";
String[]arr = new String[]{"元","拾","佰","仟","万","拾","佰"};
int j = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
if(i == arr.length - result.length())
break;
newResult = newResult + '零' + arr[j--];
}
for (int i = 0; i < result.length(); i++) {
newResult = newResult + result.charAt(i) + arr[j--];
}
return newResult;
}
}
效果图如下: