获取指定长度随机数,含大小写字母和数字
package org.sw; import java.util.Random; /** * 得到指定位数的随机数 * @author mengzw * @since 3.0 2014-2-28 */ public class DemoRandom { /** * 获取随机数 * @param length * @return */ public String getCharAndNumr(int length) { String val = ""; Random random = new Random(); for(int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字 if("char".equalsIgnoreCase(charOrNum)) // 字符串 { int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母 val += (char) (choice + random.nextInt(26)); } else if("num".equalsIgnoreCase(charOrNum)) // 数字 { val += String.valueOf(random.nextInt(10)); } } return val; } public static void main(String[] args) { DemoRandom dr = new DemoRandom(); String random = dr.getCharAndNumr(13); System.out.println(random); } }