java输入数字输出中文
时间: 2023-11-24 17:40:01 浏览: 70
Java 数字转换成中文读法
4星 · 用户满意度95%
以下是一个 Java 程序,可以将输入的数字转换为中文大写:
```java
import java.util.Scanner;
public class NumberToChinese {
private static final String[] CN_NUM = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
private static final String[] CN_UNIT = { "", "拾", "佰", "仟" };
private static final String[] CN_SECTION = { "", "万", "亿", "万亿" };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个数字:");
long num = sc.nextLong();
System.out.println(numberToChinese(num));
}
public static String numberToChinese(long num) {
if (num == 0) {
return CN_NUM[0];
}
String result = "";
int section = 0;
while (num > 0) {
int n = (int) (num % 10000);
if (n != 0) {
String s = "";
int unit = 0;
while (n > 0) {
int d = n % 10;
if (d != 0) {
s = CN_NUM[d] + CN_UNIT[unit] + s;
} else if (!s.startsWith(CN_NUM[0])) {
s = CN_NUM[0] + s;
}
n /= 10;
unit++;
}
result = s + CN_SECTION[section] + result;
} else {
if (!result.startsWith(CN_NUM[0])) {
result = CN_NUM[0] + result;
}
}
num /= 10000;
section++;
}
return result;
}
}
```
当输入一个数字时,程序会将其转换为中文大写并输出。例如,输入 123456789,输出壹亿贰仟叁佰肆十五万陆仟柒佰捌十九。
阅读全文