Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过十位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error”;
关键字提示:and,billion,million,thousand,hundred。
import java.util.Scanner; public class Main { static String[] dict=generate(); public static void main(String[] args) throws Exception { Scanner scanner=new Scanner(System.in); try { long x=scanner.nextLong(); if(Long.toString(x).length()>10) { System.out.println("error"); scanner.close();return; } System.out.println(parse(x)); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("error"); } scanner.close(); } public static String parse(long data) { StringBuilder stringBuilder=new StringBuilder(); if(data>=1000000000) { int t=(int)(data/1000000000); stringBuilder.append(baiwei(t)+" billion "); data=data%1000000000; } if(data>=1000000) { int t=(int)(data/1000000); stringBuilder.append(baiwei(t)+" million "); data=data%1000000; } if(data>=1000) { int t=(int)(data/1000); stringBuilder.append(baiwei(t)+" thousand "); data=data%1000; } if(data>0) { stringBuilder.append(baiwei((int)data)); } return stringBuilder.toString(); } public static String baiwei(int t) { if(t>100) return dict[t/100]+" hundred and "+dict[t%100]; else if(t==100) return dict[1]+" hundred "; else return dict[t%100]; } public static String[] generate() { String[] gewei={"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten"}; String[] shiji={"eleven", "twelve", "thirteen", "forty","fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; String[] shiwei={ "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; String[] strings=new String[100]; for(int i=1;i<=99;i++) { if(i<=10) { strings[i]=gewei[i]; } else if(i>10 && i<20) { strings[i]=shiji[i-11]; } else if(i>=20 && i<=99) { int s=i/10; int g=i%10; if(g>0) { strings[i]=shiwei[s-2]+" "+gewei[g]; } else { strings[i]=shiwei[s-2]; } } } return strings; } }