一个将阿拉伯数字转换为中文读法的Java代码例子

java 群里的老大出的题目,经过思考,做了这段程序,基本上比较灵活,由于初始化只定义到“亿”,因此最大能转换的也就是 到多少多少亿,如果需要能适应“兆”的读法,则需增加修改代码:

  sUnit = new String[2];
  sUnit[0] = "万";
  sUnit[1] = "亿";
  sUnit[2] = "兆";
  sUnitNum = new int[2];
  sUnitNum[0] = 4;
  sUnitNum[1] = 8;
  sUnitNum[1] = 16;

完整代码如下:

package test;  
import java.io.*;  
public class TestN2C_2 {  
 private String[] bUnit; // 基本单位 十、百、千
 private String[] sUnit; // 高级单位 万、亿
 private int[] sUnitNum; // 高级单位 万、亿 位数
 private String[] NumberStr; // 数字-中文对照
 private boolean zeroSign; // 连续零 标识
 void init() {
  NumberStr = new String[10];
  NumberStr[0] = "零";
  NumberStr[1] = "壹";
  NumberStr[2] = "贰";
  NumberStr[3] = "叁";
  NumberStr[4] = "肆";
  NumberStr[5] = "伍";
  NumberStr[6] = "陆";
  NumberStr[7] = "柒";
  NumberStr[8] = "捌";
  NumberStr[9] = "玖";
  bUnit = new String[4];
  bUnit[0] = "";
  bUnit[1] = "拾";
  bUnit[2] = "佰";
  bUnit[3] = "仟";
  sUnit = new String[2];
  sUnit[0] = "万";
  sUnit[1] = "亿";
  sUnitNum = new int[2];
  sUnitNum[0] = 4;
  sUnitNum[1] = 8;
  zeroSign = true;
 }
 String multi(String NumStr) {
  String xNumber = "";
  String xSUnit = "";
  String tempNumber = "";
  init();
  int i = 0; // 位数计数器
  while (NumStr.length() > 0) {
   if (NumStr.length() > 4) {
    tempNumber = NumStr.substring(NumStr.length() - 4);
    NumStr = NumStr.substring(0, NumStr.length() - 4);
   } else {
    tempNumber = NumStr;
    NumStr = "";
   }
   xSUnit = "";
   for (int j = sUnitNum.length - 1; j >= 0 && i > 0; j--) {
    int y = i % sUnitNum[j];
    if (y == 0) {
     xSUnit = sUnit[j];
     j = -1;
    }
   }
   for (int j = tempNumber.length() - 1; j >= 0; j--) {
    int x = Integer.parseInt(tempNumber.substring(j, j + 1));
    int y = (tempNumber.length() - j - 1) % 4;
    if (x != 0) {
     xNumber = xSUnit + xNumber;
     xNumber = bUnit[y] + xNumber;
     xNumber = NumberStr[x] + xNumber;
     zeroSign = false;
    } else {
     if (!zeroSign) {
      xNumber = xSUnit + NumberStr[x] + xNumber;
     } else if (xSUnit.length() > 0) {
      xNumber = xSUnit + xNumber;
     }
     zeroSign = true;
    }
    xSUnit = "";
   }
   i = i + 4;
  }
  return xNumber;
 }
 public static void main(String[] args) {
  try {
   System.out.println("请输入要转换的数字:");
   BufferedReader br = new BufferedReader(new InputStreamReader(
     System.in));
   String s = br.readLine();
   TestN2C_2 m = new TestN2C_2();
   System.out.print(s + " = " + m.multi(s));
  } catch (IOException e) {
  }
 }
}

转自:http://blog.sina.com.cn/s/blog_48f0b3630100037g.html