疯狂讲义在介绍强制类型转换时,介绍了生成六位随机小写字母的程序;
思想:
小写字母的ascii码为97开始的26个字母;
用(int)(math.random()*26)来随机0~25之间的整数;接着加上97转为小写字母的整数范围;然后用强制类型转换(char)来转换
问题:如果要生成的随机字符串中包含大小写字母呢?
我给出了两种办法:
一种是从大写字母A到小写字母z结束,注意其中包含了除字母外的6个字符;
第二种是设定范围就是大小写字母,用数组的方式随机
代码如下:
[java] view plain copy
public class test
{
/** pubic classname is the same of the name of file
*/
public static void main(String[] args)
{
//生成一个包含大小写字母的随机6位字符串;方法1
String randomcode = "";
for(int i=0;i<6;i++)
{
//52个字母与6个大小写字母间的符号;范围为91~96
int value = (int)(Math.random()*58+65);
while(value>=91 && value<=96)
value = (int)(Math.random()*58+65);
randomcode = randomcode + (char)value;
}
System.out.println(randomcode);
//用字符数组的方式随机
String randomcode2 = "";
String model = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] m = model.toCharArray();
for (int j=0;j<6 ;j++ )
{
char c = m[(int)(Math.random()*52)];
randomcode2 = randomcode2 + c;
}
System.out.println(randomcode2);
}
}