随机生成字母和数字的字符串工具类

废话少说,直接扔代码,我还要赶着去吃晚饭呢,饿死宝宝了,代码如下:

package com.kuang.utils;

/**
 * @author ygl
 * @description
 * @date 2020/12/2 16:05
 */

import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 生成随机数当作getItemID
 * n : 需要的长度
 * @return
 */
@Component
public final class RandomUtil {
    
    
    public static String getItemID( int n )
    {
    
    
        String val = "";
        Random random = new Random();
        for ( int i = 0; i < n; 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 + "!!!!"); 1,0,1,1,1,0,0
                val += (char) ( nextInt + random.nextInt( 26 ) );
            }
            else if ( "num".equalsIgnoreCase( str ) )
            {
    
     // 产生数字
                val += String.valueOf( random.nextInt( 10 ) );
            }
        }
        return val;
    }
}

有问题的话大家可以在下面留言哈,吃饭去喽,啊哈。

猜你喜欢

转载自blog.csdn.net/weixin_45150104/article/details/110671521