我把第二种方式做出来了.代码如下:
package Day12;
class Demo
{
public int[] getNum(int year) //获取一个数值每一位的方法
{
int arr[]=new int[4];
for(int i=(arr.length-1),x=10;i>=0;i--)
{
arr[i]=year%x; //取一个整数的每一位数的方法 %10得低位,从个位开始把值赋给arr[i],
year/=x;// 除10使数减少.因为最低位已经取得了.
}
return arr;
}
public static String newYear(int year) //实现汉字打印年份的第一种方法.
{
String[] num={"零","一","二","三","四","五","六","七","八","九"};
Demo d=new Demo();
String newyear="";
int arr[]=d.getNum(year);
for(int i=0;i<arr.length;i++)
newyear+=num[arr[i]];
return newyear;
}
public static String getYear(int year) //实现汉化打印年份的第二种,通过String类与字符数组的转换获得
{
String[] num={"零","一","二","三","四","五","六","七","八","九"};
int[] nums=new int[4];
String newyear="";
String toYear=Integer.toString(year); //将year年转换成字符串
char[] c_num=toYear.toCharArray(); //将year字符串转成字符数组
for(int i=0;i<nums.length;i++)
{
nums[i]=(int)(c_num[i])-48; //将字符数组转成单个数,其实是String输出的角标,char类型转int型后,值发生改变-48
//newyear+=num[nums[i]]; //将num字符串的角标连起来.组成汉字年份.
//System.out.println(num[nums[i]]);
newyear+=num[nums[i]];
}
return newyear;
}
public static void main(String[] args)
{
System.out.println(getYear(2012));
System.out.println(newYear(2004));
}
}
打印结果:
二零一二
二零零四
|