zoukankan      html  css  js  c++  java
  • 【Java算法】获得一个随机字符串

    package suanfa;
    
    import java.util.Random;
    
    public class RandomStr {
    
    	public static String getRandomStr(int length) {
    		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
    		int randomNum;
    		char randomChar;
    		Random random = new Random();
    		// StringBuffer类型的可以append增加字符
    		StringBuffer str = new StringBuffer();
    
    		for (int i = 0; i < length; i++) {
    			// 可生成[0,n)之间的整数,获得随机位置
    			randomNum = random.nextInt(base.length());
    			// 获得随机位置对应的字符
    			randomChar = base.charAt(randomNum);
    			// 组成一个随机字符串
    			str.append(randomChar);
    		}
    		return str.toString();
    	}
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		System.out.println(getRandomStr(8));
    	}
    
    }
    

      

  • 相关阅读:
    2016/09/18
    2016/09/16
    2016/09/15
    2016/09/14
    2016/09/13
    2016/09/12
    2016/09/03
    2016/09/02
    HDU1850 Being a Good Boy in Spring Festival(NIM)
    POJ3070 Fibonacci(矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/Jourly/p/7073583.html
Copyright © 2011-2022 走看看