package contest.numtochi;
import java.util.HashMap;
import java.util.Scanner;
public class NumToChi{
//创建数字和中文数字一一对应的映射
private HashMap<Integer, String> map;
//创建位数和中文单位的一一映射
private HashMap<Integer, String> unit;
// 判断输入的字符串是否全是数字
public boolean isNum(String str) {
boolean flag = true;
try {
Integer.parseInt(str);
} catch (Exception e) {
flag = false;
System.out.println("用户输入的字符不是数字");
}
return flag;
}
// 给map赋值,使数字和中文数字意义对应
public void initMap() {
map = new HashMap<Integer, String>();
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, "九");
}
// 给unit赋值,表示表示数字单位
public void initUnit() {
unit = new HashMap<Integer, String>();
unit.put(0, "");
unit.put(1, "十");
unit.put(2, "百");
unit.put(3, "千");
unit.put(4, "万");
unit.put(5, "十");
unit.put(6, "百");
unit.put(7, "千");
}
// 将全是数字的字符串转换成中文数字表示的方法
public String change(String str) {
String chinese = "";
// 去掉头部的0
str = String.valueOf(Integer.parseInt(str));
// 将数字转换成中文数字
for (int i = 0; i < str.length(); i++) {
int index = str.charAt(i) - 48;
chinese += map.get(index);
chinese += unit.get(str.length() - i - 1);
}
// 处理字符串中的零
while ((chinese.indexOf("零十") != -1) || (chinese.indexOf("零百") != -1)
|| (chinese.indexOf("零千") != -1)
|| (chinese.indexOf("零零") != -1)) {
if (chinese.indexOf("零十") != -1) {
chinese = chinese.replaceAll("零十", "零");
}
if (chinese.indexOf("零百") != -1) {
chinese = chinese.replaceAll("零百", "零");
}
if (chinese.indexOf("零千") != -1) {
chinese = chinese.replaceAll("零千", "零");
}
if (chinese.indexOf("零零") != -1) {
chinese = chinese.replaceAll("零零", "零");
}
}
if(chinese.indexOf("零万") != -1){
chinese = chinese.replaceAll("零万", "万");
}
//如果结尾有零
if(chinese.lastIndexOf("零") == chinese.length()-1){
chinese = chinese.substring(0, chinese.length()-1);
}
return chinese;
}
public static void main(String[] args) {
NumToChi ntc = new NumToChi();
System.out.println("请输入要转换的数字字符串:");
Scanner s = new Scanner(System.in);
String str = s.next();
if (ntc.isNum(str)) {
ntc.initMap();
ntc.initUnit();
System.out.println(ntc.change(str));
}
}
}
将阿拉伯数字转换成中文数字表示
最新推荐文章于 2024-08-16 23:08:28 发布