1 package demo; 2 import java.util.Random; 3 4 /** 5 * 生成字母+数字的随机数 6 * @author sy 7 * 8 */ 9 public class Demo{ 10 11 public static void main(String[] args){ 12 System.out.println(getStringRandom(6)); 13 } 14 15 public static String getStringRandom(int length) { 16 17 String val = ""; 18 Random random = new Random(); 19 //参数length,表示生成几位随机数 20 for(int i = 0; i < length; i++) { 21 String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; 22 //输出字母还是数字 23 if("char".equalsIgnoreCase(charOrNum)){ 24 //输出是大写字母还是小写字母 25 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; 26 val += (char)(random.nextInt(26) + temp); 27 }else if("num".equalsIgnoreCase(charOrNum)) { 28 val += String.valueOf(random.nextInt(10)); 29 } 30 } 31 return val; 32 } 33 34 }