2017-5-12-01 输入数字输出汉字读法
输入数字输出汉字读法
(参考:http://tieba.baidu.com/p/4101663044)
例如,输入7865,输出:七千八百六十五
解决一:
(事先定义一个装有“个十百千万”,一个装有“零一二三四五.....”的数组或者集合A和B,首先获取用户输入数字的长度,然后获得各个位,每个位数就是B的下标,然后长度就是A的下标减一,比如: 485 4对应B[4]为“四”,A[2]为百 8对应B[8]为八,A[1]为十 。)
public class Test { public static void main(String[] args) throws IOException { String [] A={"","十","百","千","万"}; String [] B={"零","一","二","三","四","五","六","七","八","九"}; BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); String inputString = buffer.readLine(); //String inputString ="4859"; StringBuilder result= new StringBuilder(); int intNum= Integer.parseInt(inputString); int len = inputString.length(); for(int i=0;i<len;i++) { int yu = intNum%10; result.insert(0, A[i]); result.insert(0, B[yu]); intNum/=10; } System.out.println(result.toString()); } }
解决二:
(定好模板:x万x千x百x十x,逐个提取阿拉伯数字,自右向左替换模板的x,当然阿拉伯数字还是要映射成中文,最后把替换后的模板由左数起至最后一个x的下一位截掉,剩下的就是结果)
public class Test { public static void main(String[] args) throws IOException { String template= "x万x千x百x十x"; char[] ch=template.toCharArray(); char [] B={'零','一','二','三','四','五','六','七','八','九'}; BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); String inputString = buffer.readLine(); //String inputString ="4859"; int intNum= Integer.parseInt(inputString); int len = inputString.length(); for(int i=0;i<len;i++) { int yu = intNum%10; int index= template.lastIndexOf("x"); ch[index]=B[yu]; intNum/=10; template=String.valueOf(ch); } int index= template.lastIndexOf("x"); System.out.println(template.substring(index+2)); } }