天天看點

數字轉換為漢字顯示

package andycpp;

import java.io.ioexception;

import java.util.hashmap;

import java.util.map;

import java.util.regex.matcher;

import java.util.regex.pattern;

public class changeatoc {

/**

* @param args

* @throws exception

*/

private static map map =null;

static {

map = new hashmap();

map.put(0, "零");

map.put(1, "一");

map.put(2, "二");

map.put(3, "三");

map.put(4, "四");

map.put(5, "五");

map.put(6, "六");

map.put(7, "七");

map.put(8, "八");

map.put(9, "九");

}

public static void main(string[] args) throws exception {

/*****以下為字元輸入部分*****/

byte[] a = new byte[1024];

string str = null;

string head= null;

int size = 0;

while (true) {

int read = 0;

try {

read = system.in.read();

} catch (ioexception e) {

e.printstacktrace();

a[size++] = (byte) read;

// 為換行時

if (read == 10) {

str = new string(a, 0, size);

break;

/*****輸入完成,進行格式校驗*****/

pattern p = pattern.compile("\\d+\\.\\d+");

matcher mt = p.matcher(str);

stringbuffer sb = new stringbuffer();

if (mt.find()) {

string[] strs = mt.group().split("\\.");

int ints = integer.parseint(strs[0]);

if (ints == 0) {

head = "零";

} else {

for (int i = 1; ints != 0;) {

sb.append(map.get(ints % 10));

unitchinese(sb, i);

ints /= 10;

i++;

// 細節處理

head = sb.reverse().substring(1, sb.length());

if (head.endswith("零")) {

head = head.substring(0, head.length() - 1);

head = replacezero("零十", head);

head = replacezero("零百", head);

head = replacezero("零千", head);

head = replacezero("零萬", head);

while (head.startswith("一十")) {

head = head.substring(1, head.length());

system.out.println(head);

string end =strs[1];

sb =new stringbuffer();

for (int i = 0; i < end.length(); i++) {

sb.append(map.get(integer.parseint(end.substring(i,i+1))));

//合并

system.out.println(head+"點"+sb.tostring());

throw new exception("字元輸入不合法");

//去掉文法中的零千、零萬、零十、零百

private static string replacezero(string str, string head) {

while(head.lastindexof(str)!=-1){

head = head.replace(str, "");

return head;

private static void unitchinese(stringbuffer sb, int i) {

if(i==1){

sb.append("十");

}else if(i==2){

sb.append("百");

}else if(i==3){

sb.append("千");

}else if(i==4){

sb.append("萬");

}else if(i==5){

}else if(i==6){

}else if(i==7){

}else if(i==8){

sb.append("億");

繼續閱讀