数字转换成人民币大写读法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
{
//汉字数字
public static String[] han={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
//单位
public static String[] unit={"元","十","百","千"};
//单位
public static String[] xunit={"角","分"};
//分割整数与小数部分,返回字符串数组
public static String[] divide(double num)
{
long zheng = (long)num;
long xiao = Math.round((num-zheng)*100);
if(xiao!=0)
{
return new String[]{zheng+"",xiao+""};
}
else
{
return new String[]{zheng+"",null};
}
}
//转换成汉字,4位数
public static String toHan(double number)
{
//使用divide方法得到分割后的整数与小数部分
String[] arr=Convert.divide(number);
//整数部分
String numStr=arr[0];
//小数部分
String xiaoStr=arr[1];
String result="";
//大写字符串长度
int numlen=numStr.length();
for (int i=0;i<numlen;i++)
{
//在ASCII码中,字符串数字的ASCII码-48得到相应的数字ASCII码
//String.charAt(int num)方法得到指定位置的字符值
int num=numStr.charAt(i)-48;
//数字不为0,则添加单位,否则不添加
if(num!=0)
{
result+=han[num]+unit[numlen-1-i];
}
else
{
result+=han[num];
}
}
//若存在小数部分则进行处理
if(xiaoStr!=null)
{
for (int i=0;i<2;i++)
{
int num=xiaoStr.charAt(i)-48;
result+=han[num]+xunit[i];
}
}
return result;
}

public static void main(String[] args)
{
System.out.println(toHan(6521.1));
}
}
/*运行结果输出如下:
陆千伍百贰十壹元壹角零分
*/

按字节截子字符串

刚刚测试的时候发现java在Linux与windows下一个中文字符所代表的字节不相同,此处是在Linux下测试的,以下作为字节参考:

windows Linux
中文 2 3
英文 1 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Substr类

public class Substr
{
//sub方法
public static String sub(String s,int start,int end)
{
//把字符串s转换成字节数组
byte[] arr=s.getBytes();
//定义一个字节数组subs,用来接收子字符串
byte[] subs=new byte[arr.length];
//使用循环,令subs字节数组接收子字节
for(int i=start,j=0;i<=end;i++)
{
subs[j]=arr[i];
j++;
}
//使用subs直接用String构造函数返回子字符串
String substring = new String(subs);
return substring;
}

public static void main(String [] args)
{
String s="hello我是子字符串word";
System.out.println(s);
System.out.println("子字符串:");
System.out.println(Substr.sub(s,5,22));
}
}
/*运行输出如下:
hello我是子字符串word
子字符串:
我是子字符串*/

画圆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

//Circle类

public class Circle

{
public static void main(String[] args)
{
//圆的半径
int r = 6;
//y为纵坐标变量
for(int y=0;y<=2*r;y=y+2)
{
//求出1/2弦长
long x=Math.round(Math.sqrt(r*r-(r-y)*(r-y)));
//输出*号
for(int i=0;i<=2*r;i++)
{
//i为横坐标
if(i==r-x||i==r+x)
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
//转行
System.out.println("");
}
}

}