栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 通过Random 获取随机字母+数字+特殊字符

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 通过Random 获取随机字母+数字+特殊字符

完全随机写法:随机获取的数据  概率获得(大小字母+数字+特殊字符)的字符串

public static void main(String[] args){

        String val = "";
        Random random = new Random();
        for ( int i = 0; i < 12; i++ )
        {
            String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
            if ( "char".equalsIgnoreCase( str ) )
            { // 产生字母
                int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
                 System.out.println(nextInt + "!!!!");
                val += (char) ( nextInt+ random.nextInt( 25 ) );
            }
            else if ( "num".equalsIgnoreCase( str ) )
            { 
            // 产生数字
                val += String.valueOf( random.nextInt( 10 ) );
            } else{
                特殊字符//    
                val += String.valueOf( random.nextInt( 10 ) );
            }
        }
        System.out.println(val);
}

自定义100%获取(大小字母+数字+特殊字符)的字符串:

 public static void main(String[] args){

        String val = "";
        Random random = new Random();
        for ( int i = 0; i < 12; i++ ){
            if(i<4){
                //获取大写字母
                int nextInt = 65;
                val += (char) (nextInt+random.nextInt( 25 ) );
            }
            if(i>=4 && i<7){
                //获取数字
                int nextInt = 48;
                val += (char) (nextInt+random.nextInt( 9 ) );
            }
            if(i>=7 && i<8){
                //获取特殊符号
                int nextInt = 33;
                val += (char) (nextInt+random.nextInt( 14 ) );
            }
            if(i>=8 && i<12){
                //获取小写字符
                int nextInt = 97;
                val += (char) (nextInt+random.nextInt( 25 ) );

            }
        }
        System.out.println(val);
    }

思路:通过ASCLL表转字符(参考图)引用百度文库,仅供参考

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322452.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号