如何用java将1010转换成一千零一十

如题所述

希望可以帮到你
//可将任意整数(如1010)转换成大写形式(一千零一十)
import java.util.Scanner;

public class TestMoney {

public static void main(String[] args) {
System.out.print("请输入要转换成大写的人民币整数:");
Scanner scan = new Scanner(System.in);
String temp = scan.nextLine();
String[] str1 = { "零", "一", "二", "三", "四", "五", "六","七", "八", "九" };
String[] str2 = { "十", "百", "千", "万", "十", "百", "千", "亿" };

String res = "";

// 遍历一行中所有数字
for (int k = -1; temp.length() > 0; k++) {
// substring()截取函数,解析最后一位
int j = Integer.parseInt(temp.substring(temp.length() - 1, temp.length()));
String rtemp = str1[j];

// 数值不是0且不是个位 或者是万位或者是亿位 则去取单位
if (j != 0 && k != -1 || k % 8 == 3 || k % 8 == 7) {
rtemp += str2[k % 8];
}

// 拼在之前的前面
res = rtemp + res;

// substring()截取函数,去除最后一位
temp = temp.substring(0, temp.length() - 1);
}

// 去除后面连续的零零..
while (res.endsWith(str1[0])) {
res = res.substring(0, res.lastIndexOf(str1[0]));
}

// replaceAll()替换函数,将零零替换成零
while (res.indexOf(str1[0] + str1[0]) != -1) {
res = res.replaceAll(str1[0] + str1[0], str1[0]);
}

// replaceAll()替换函数,将 零+某个单位 这样的窜替换成 该单位 去掉单位前面的零
for (int m = 1; m < str2.length; m++) {
res = res.replaceAll(str1[0] + str2[m], str2[m]);
}

System.out.println(res);

}

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-24
public class NumConChn
{

public static void main(String[] args)
throws Exception
{

String[] units = new String[] {"十", "百", "千", "万", "十", "百", "千", "亿"};
// String[] numeric = new String[] {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[] numeric = new String[] {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};

String res = "";
String temp = "1010";

// 遍历一行中所有数字
for (int k = -1; temp.length() > 0; k++)
{
// 解析最后一位
int j = Integer.parseInt(temp.substring(temp.length() - 1, temp.length()));
String rtemp = numeric[j];

// 数值不是0且不是个位 或者是万位或者是亿位 则去取单位
if (j != 0 && k != -1 || k % 8 == 3 || k % 8 == 7)
{
rtemp += units[k % 8];
}

// 拼在之前的前面
res = rtemp + res;

// 去除最后一位
temp = temp.substring(0, temp.length() - 1);
}

// 去除后面连续的零零..
while (res.endsWith(numeric[0]))
{
res = res.substring(0, res.lastIndexOf(numeric[0]));
}

// 将零零替换成零
while (res.indexOf(numeric[0] + numeric[0]) != -1)
{
res = res.replaceAll(numeric[0] + numeric[0], numeric[0]);
}

// 将 零+某个单位 这样的窜替换成 该单位 去掉单位前面的零
for (int m = 1; m < units.length; m++)
{
res = res.replaceAll(numeric[0] + units[m], units[m]);
}

System.out.println(res);

}
}
第2个回答  2011-03-24
parseInt()这个方法是将String型转化为int型的。在API中你可以搜一下,看看具体上面怎么说。

valueOf()这个方法是将int型转回String 型。
第3个回答  2011-03-24
将0-9 替换成零到九,然后根据长度 加上 十百千万亿,例如 : 1010 先变成 一零一零
长度为四在 第一位后千 第二位加 百 第三位十
第4个回答  2011-03-24
Integer.parseInt("1010");
//parseInt()这个方法是将String型转化为int型的。在API中你可以搜一下,看看具体上面怎么说。

String.valueOf(1010);
//valueOf()这个方法是将int型转回String 型。
第5个回答  2011-03-24
for语句加%求余,取每个数位,用一个数组保存,在根据中文的习惯用if判断输出。