写了个千位以内的,比较简单,再大点就比较繁琐了。
package cn.itcast;
import java.util.Scanner;
/*
* 数字转换汉字小程序,要求如下:
1.键盘录入一个大于-1小于1000的正整数,将该整数转换成中文在控制台输出
2.除非输入数字不在规定的范围,否则可以一直进行输入转换
小于10,数字后不需要带单位
大于9小于100,数字后需要带单位”十”
大于99小于1000,数字后需要带单位”百”
数字转换成中文样式如下:
5 五
15 一十五
115 一百一十五
*/
public class Demo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] arr = {"0","1","2","3","4","5","6","7","8","9"};
String[] arr1 = {"零","一","二","三","四","五","六","七","八","九"};
while(true){
System.out.println("请输入一个大于-1小于1000的正整数");
String s = sc.next();
if(!s.matches("\\d+")){
System.out.println("不是正整数");
return;
}
for (int i = 0; i < arr1.length; i++) {
s=s.replace(arr[i], arr1[i]);
}
StringBuilder sb = new StringBuilder();
sb.append(s);
if(sb.length()==1){
System.out.println(sb);
}else if(sb.length()==2){
sb.insert(1, "十");
System.out.println(sb);
}else if(sb.length()==3){
sb.insert(1, "百");
sb.insert(3, "十");
System.out.println(sb);
}else{
System.out.println("数字不在规定范围");
return;
}
}
}
} |