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; //数字的长度 boolean hasZero = false; //是否有0 //是否从第1位,第5为,第9位……开始。用来去除个位上的“零” boolean zeroFromGeWei = true; //判断是否是合法数字 if(!input.matches(regix)){ throw new RuntimeException("对不起,你输入的不是数字!"); } // 将String数字变成int数组 for (int i = 0; i < num.length; i++) { num[i] = Integer.parseInt(String.valueOf(input.charAt(i))); } // 将str1的元素与数字一一对应 for (int i = 0; i < str1.length; i++) { map1.put(i, str1[i]); } //开始转换字符串 for(int i = len - 1 ; i>= 0 ; i--){ int position = len - i -1; if ( position % 4 == 0) zeroFromGeWei = true; // 如果不是个位,每四位加个万或亿字,交替添加 if(i != (len - 1) && ( position % 4 == 0)){ if (hasZero ) { sb.insert(0,"零"); //在万亿之前的0数字,要处理完 hasZero = false; } if((position % 8 == 0)){ sb.insert(0,"亿"); } else { sb.insert(0,"万"); } } //判断数字字符是不是0字符 if (num[i] != 0){ if (hasZero && !zeroFromGeWei ) { sb.insert(0,"零"); } hasZero = false; zeroFromGeWei = false; sb.insert(0,map1.get(num[i])); switch (position % 4) { case 1: sb.insert(1,"拾"); break; case 2: sb.insert(1,"百"); break; case 3: sb.insert(1,"千"); break; default: break; } } else { hasZero = true; } } //去除零万的情况 int index = sb.indexOf("零万"); while(index != -1){ System.out.println(sb.toString()); System.out.println("index=" + index); sb.delete(index, index+2); index = sb.indexOf("零万"); } return sb.toString(); } }