Java实现中文数字转换为阿拉伯数字

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class testz {

	static int[] shuzi = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	static String[] hanzi = { "一", "二", "三", "四", "五", "六", "七", "八", "九" };
	static char[] hanziC = { '一', '二', '三', '四', '五', '六', '七', '八', '九' };
	static char[] w1 = { '千', '百', '十' };
	static Map a = new TreeMap();
	static Map b = new TreeMap();

	public static void main(String[] args) {
		for (int i = 0; i < 9; i++) {
			a.put(hanzi[i], shuzi[i]);
			b.put(hanziC[i], shuzi[i]);
		}
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入一个汉字数字:");
		System.out.println("列如:五十八   ==  58");
		String str = scan.nextLine();
		String yw;
		String ww;
		String qw;
		if (str.indexOf("亿") != -1) {
			String[] spy = str.split("亿");
			if (spy.length == 1) {
				yw = spy[0];
				System.out.println(yw(yw));
			} else {
				yw = spy[0];
				String[] spwq = spy[1].split("万");
				if (spwq.length == 1) {
					ww = spwq[0];
					System.out.println(yw(yw) + ww(ww));
				} else {
					yw = spy[0];
					ww = spwq[0];
					qw = spwq[1];
					System.out.println(yw(yw) + ww(ww) + qw(qw));
				}
			}
		} else if (str.indexOf("万") != -1) {
			String[] spwq = str.split("万");
			if (spwq.length == 1) {
				ww = spwq[0];
				System.out.println(ww(ww));
			} else {
				ww = spwq[0];
				qw = spwq[1];
				System.out.println(ww(ww) + qw(qw));
			}
		} else {
			System.out.println(qw(str));
		}
	}
	//计算9999位
	public static int qw(String str) {
		return gj(str);
	}
	//计算9999万位
	public static int ww(String str) {
		return gj(str) * 10000;
	}
	//计算24亿(int最大是24亿多)
	public static int yw(String str) {
		return gj(str) * 10000 * 10000;
	}
	//工具方法,用于计算4个位,把亿,万,进行拆分
	public static int gj(String str) {
		int[] sum = { 0, 0, 0, 0 };
		int[] sum1 = { 0, 0, 0, 0 };
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == w1[0]) {
				sum[0] = b.get(str.charAt(i - 1));
			} else if (str.charAt(i) == w1[1]) {
				sum[1] = b.get(str.charAt(i - 1));
			} else if (str.charAt(i) == w1[2]) {
				if (str.charAt(0) == '十' || (str.charAt(0) == '零' && b.get(str.charAt(1)) == null)
						|| str.charAt(i - 1) == '零') {
					sum[2] = 1;
				} else {
					sum[2] = b.get(str.charAt(i - 1));
				}
			}
		}
		if (a.get(str.substring(str.length() - 1, str.length())) != null) {

			sum[3] = a.get(str.substring(str.length() - 1, str.length()));
		} else {
			sum[3] = 0;
		}
		if (sum[0] != 0) {
			sum1[0] = sum[0] * 1000;
		}
		if (sum[1] != 0) {
			sum1[1] = sum[1] * 100;
		}
		if (sum[2] != 0) {
			sum1[2] = sum[2] * 10;
		}
		if (sum[3] != 0) {
			sum1[3] = sum[3];
		}
		return sum1[0] + sum1[1] + sum1[2] + sum1[3];
	}
}

 

你可能感兴趣的:(java)