标签:
课堂练习1:
结果截图:
原因分析:把a的值赋给b的同时也将a的存储地址赋给了b,b指向a的地址,a的长度为3,所以b的长度也为3。
动手动脑1:
结果截图:
动手动脑2:
源程序:
public class Num2Rmb {
private String[] hanArr = {"零","一","二","三","四","五","六","七","八","九"};
private String[] yuanArr = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
private String[] unitArr = {"十" , "百" , "千","万","十万","百万"};
private String[] daxieArr ={"拾","佰","仟","万","拾万","佰万"};
/**
* 把一个四位的数字字符串变成汉字字符串
* @param numStr 需要被转换的四位的数字字符串
* @return 四位的数字字符串被转换成的汉字字符串。
*/
private String toHanStr(String numStr)
{
String result = "";
int numLen = numStr.length();
//依次遍历数字字符串的每一位数字
for (int i = 0 ; i < numLen ; i++ )
{
//把char型数字转换成的int型数字,因为它们的ASCII码值恰好相差48
//因此把char型数字减去48得到int型数字,例如‘4‘被转换成4。
int num = numStr.charAt(i) - 48;
//如果不是最后一位数字,而且数字不是零,则需要添加单位(千、百、十)
if ( i != numLen - 1 && num != 0)
{
result += hanArr[num] + unitArr[numLen - 2 - i];
}
//否则不要添加单位
else
{
//上一个数是否为“零”,不为“零”时就添加
if(result.length()>0 && hanArr[num].equals("零") && result.charAt(result.length()-1)==‘零‘)
continue;
result += hanArr[num];
}
}
//只有个位数,直接返回
if(result.length()==1)
return result;
int index=result.length()-1;
while(result.charAt(index)==‘零‘){
index--;
}
if(index!=result.length()-1)
return result.substring(0,index+1);
else {
return result;
}
}
private String HanziyuanStr(String numStr)
{
String result = "";
int numLen = numStr.length();
for (int i = 0 ; i < numLen ; i++ )
{
int num = numStr.charAt(i) - 48;
if ( i != numLen - 1 && num != 0)
{
result += yuanArr[num] + daxieArr[numLen - 2 - i];
}
else
{
if(result.length()>0 && yuanArr[num].equals("零") && result.charAt(result.length()-1)==‘零‘)
continue;
result += yuanArr[num];
}
}
if(result.length()==1)
return result;
int index=result.length()-1;
while(result.charAt(index)==‘零‘){
index--;
}
if(index!=result.length()-1)
return result.substring(0,index+1);
else {
return result;
}
}
public static void main(String[] args) {
Num2Rmb nr = new Num2Rmb();
//测试把一个四位的数字字符串变成汉字字符串
System.out.println(nr.toHanStr("7"));
System.out.println(nr.HanziyuanStr("7")+"元");
System.out.println(nr.toHanStr("20"));
System.out.println(nr.HanziyuanStr("20")+"元");
System.out.println(nr.toHanStr("810"));
System.out.println(nr.HanziyuanStr("810")+"元");
System.out.println(nr.toHanStr("1024"));
System.out.println(nr.HanziyuanStr("1024")+"元");
System.out.println(nr.toHanStr("11111"));
System.out.println(nr.HanziyuanStr("11111")+"元");
System.out.println(nr.toHanStr("109647"));
System.out.println(nr.HanziyuanStr("109647")+"元");
System.out.println(nr.toHanStr("6437659"));
System.out.println(nr.HanziyuanStr("6437659")+"元");
}
}
结果截图:
标签:
原文地址:http://www.cnblogs.com/hy-666/p/4931637.html