日期:2014-05-20 浏览次数:20776 次
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ArabToChinese { public Stack<String>stack; public ArabToChinese(){ stack=new Stack<String>(); } public void pushToStack(Stack<String>stack,char c){ switch(c){ case '0': stack.push("零"); break; case '1': stack.push("壹"); break; case '2': stack.push("贰"); break; case '3': stack.push("叁"); break; case '4': stack.push("肆"); break; case '5': stack.push("伍"); break; case '6': stack.push("陆"); break; case '7': stack.push("柒"); break; case '8': stack.push("捌"); break; case '9': stack.push("玖"); break; } } public void pushToStack_(Stack<String>stack,String s){ int digit1=5; int digit2=9; int digit3=1; for(int i=s.length()-1,j=0,k=0;i>=0;i--){ char c=s.charAt(i); j++; k++; if(k==2){ stack.push("拾"); } else if(k==3){ stack.push("佰"); } else if(k==4){ stack.push("仟"); k=0; } if(j==digit1){ stack.push("萬"); digit1+=8; } if(j==digit2){ stack.push("亿"); digit2+=8; } if(j==digit3&&c=='0') { digit3+=4; continue; } else pushToStack(stack,c); } } public String popToString(Stack<String>stack){ String s=""; StringBuffer buffer=new StringBuffer(); while(stack.empty()==false){ buffer.append((String)stack.pop()); } s=buffer.toString(); s=s.replaceAll("零仟","零"); s=s.replaceAll("零佰","零"); s=s.replaceAll("零拾","零"); s=s.replaceAll("[零]+","零"); s=s.replaceAll("零萬","萬"); s=s.replaceAll("零亿","亿"); s=s.replace("零角",""); s=s.replace("零分",""); return s; } public static void main(String args[]) throws IOException{ boolean available=false; String s=""; String s1=""; System.out.print("请输入一个数字:"); while(!available){ BufferedReader buffer; buffer=new BufferedReader(new InputStreamReader(System.in)); s=buffer.readLine(); Pattern pattern=Pattern.compile("^[^0][0-9]+(.[0-9]{1,2})$"); Matcher matcher=pattern.matcher(s); boolean isMatched=matcher.find(); if(isMatched==true){ available=true; } else System.out.println("你输入的数字有错误,请重新输入:"); } ArabToChinese atc=new ArabToChinese(); int index=s.indexOf('.'); if(index!=-1){ s1=s.substring(index+1); s=s.substring(0,index); atc.pushToStack_(atc.stack, s); s=atc.popToString(atc.stack)+"圆"; if(s1.length()==1){ s1=s1+"0"; } for(int i=1,j=0;i>=0;i--){ char c=s1.charAt(i); j++; if(j==1){ atc.stack.push("分"); } if(j==2){ atc.stack.push("角"); } atc.pushToStack(atc.stack,c); } s1=atc.popToString(atc.stack); System.out.println("转换后的金钱数字为:"+s+s1); } else {atc.pushToStack_(atc.stack,s); s=atc.popToString(atc.stack)+"圆"; s=s.replace("零圆","圆"); System.out.println("转换后的金钱数字为:"+s); } } }