求java金额转换优化
这是我写的代码,只能转换为万元以下,比如我把101000001010 转换为 壹仟零壹拾億零壹仟零壹拾圆整。
还不行,求大神优化一下
import java.util.Scanner;
import java.util.TreeMap;
public class TenTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你转换的数字:");
String input = null;
do {
input = sc.next();
System.out.println("对不起,你输入的不是数字,请重新输入:");
} while (!isValid(input));
// 将String数字变成int数组
int[] num = new int[input.length()];
for (int i = 0; i < num.length; i++) {
num[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
moneyTransMethod(num);
}
public static void moneyTransMethod(int[] num) {
String[] str1 = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "玐", "玖" };
String[] str2 = { "拾", "佰", "仟", "万", "亿" };
final String zheng = "整";
TreeMap<Integer, String> map1 = new TreeMap<Integer, String>();
TreeMap<Integer, String> map2 = new TreeMap<Integer, String>();
// 将str1的元素与数字一一对应
for (int i = 0; i < str1.length; i++) {
map1.put(i, str1[i]);
}
// 将str2的元素与数字一一对应
for (int i = 0; i < str2.length; i++) {
map2.put(i, str2[i]);
}
StringBuilder sb = new StringBuilder();
int len = num.length;
for (int i = 0; i < num.length; i++) {
if (num.length != 1 && num.length < 6) {
String strVal = map2.get(len - 2 - i);
sb.append(map1.get(num[i])).append(strVal);// ?
if (strVal == null) {
sb.delete(sb.lastIndexOf("n"), sb.lastIndexOf("l") + 1);
}
} else if (num.length == 1) {
sb.append(map1.get(num[i]));
}
}
System.out.println(sb.toString());
}
public static boolean isValid(String input) {
String regix = "[0-9]+";
return input.matches(regix);
}
}
------解决方案--------------------再次修改!
package com.xiuxiu.huobi;
import java.util.Scanner;
import java.util.TreeMap;
public class TenTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你转换的数字:");
String input = sc.next();
System.out.println(integerTransGBK(input));
}
private static String integerTransGBK(String input) {
String regix = "[0-9]+";
int[] num = new int[input.length()];
String[] str1 = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "玐", "玖" };
TreeMap<Integer, String> map1 = new TreeMap<Integer, String>();
StringBuilder sb = new StringBuilder();
int len = num.length; //数字的长度