您的位置:首页 > 编程语言 > Java开发

java第一天:生成六位的随机字母(包含大小写)

2014-12-05 15:28 363 查看
疯狂讲义在介绍强制类型转换时,介绍了生成六位随机小写字母的程序;

思想:

小写字母的ascii码为97开始的26个字母;

用(int)(math.random()*26)来随机0~25之间的整数;接着加上97转为小写字母的整数范围;然后用强制类型转换(char)来转换

问题:如果要生成的随机字符串中包含大小写字母呢?

我给出了两种办法:

一种是从大写字母A到小写字母z结束,注意其中包含了除字母外的6个字符;

第二种是设定范围就是大小写字母,用数组的方式随机

代码如下:

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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐