用Java写一个程序:在键盘输入阿拉伯数字,将它转化为中文
时间: 2024-04-29 09:22:31 浏览: 59
好的,这个问题我可以回答。以下是Java代码示例:
```
import java.util.Scanner;
public class NumToChinese {
private static final String[] CHINESE_NUMBERS = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
private static final String[] CHINESE_UNITS = {"","拾","佰","仟","万","亿"};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(convertToChinese(num));
}
private static String convertToChinese(int num) {
if (num == 0) {
return CHINESE_NUMBERS[0];
}
StringBuilder sb = new StringBuilder();
if (num < 0) {
sb.append("负");
num = -num;
}
String numStr = String.valueOf(num);
int length = numStr.length();
boolean hasZero = false;
for (int i = 0; i < length; i++) {
int digit = numStr.charAt(i) - '0';
int unitPos = length - 1 - i;
if (digit == 0) {
hasZero = true;
if (unitPos == 4 || unitPos == 8) {
sb.append(CHINESE_UNITS[unitPos]);
hasZero = false;
}
} else {
if (hasZero) {
sb.append(CHINESE_NUMBERS[0]);
hasZero = false;
}
sb.append(CHINESE_NUMBERS[digit]).append(CHINESE_UNITS[unitPos]);
}
}
return sb.toString();
}
}
```
这个程序可以将输入的阿拉伯数字转换为相应的中文数字。例如,输入12345,则输出"壹万贰仟叁佰肆拾伍"。
阅读全文