代码逻辑相对粗糙,将就看吧。
public void testCode(){ char[] code=new char[6]; for (int i=0;i<code.length;i++) { int index = 0; //循环 while (true) { //索引随机 index = new Random().ints(0,6).findFirst().getAsInt(); //保证不在重复位置 if (code[index]==0) { //小写字母随机 char base = (char) (Math.random() * 26 + 'a'); //0-9数字随机 char num = (char) (Math.random() * 9 + 48); int flag = new Random().nextInt(9); //字母或数字随机选择 if (flag % 2 == 0) { code[index] = base; break; } else { code[index] = num; break; } } } } System.out.println(String.valueOf(code)); }