生成六位的随机字母(包含大小写)

疯狂讲义在介绍强制类型转换时,介绍了生成六位随机小写字母的程序;

思想:

小写字母的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);  


}  

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值