代码如下:
数字密码:
方法(1):
public static void main(String[] args) {
String code="";
Random rand=new Random();//生成随机数
for(int a=0;a<6;a++){
code+=rand.nextInt(10);//生成6位验证码
}
system.out.println("随机数为"+code);
}
方法(2):
封装的数字密码:
public static int getRandNum(int min, int max) {
int randNum = min + (int)(Math.random() * ((max - min) + 1));
return randNum;
}
@Test
public void rand(){
System.out.println("随机数为" + getRandNum(1,999999));
}
方法(3):
数字加字母的密码:
public class StringRandom {
//生成随机数字和字母,
public String getStringRandom(int length) {
String val = "";
Random random = new Random();
//length为几位密码
for(int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
//输出字母还是数字
if( "char".equalsIgnoreCase(charOrNum) ) {
//输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char)(random.nextInt(26) + temp);
} else if( "num".equalsIgnoreCase(charOrNum) ) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
//生产的密码包括位数
public static void main(String[] args) {
StringRandom test = new StringRandom();
System.out.println(test.getStringRandom(6));
}
}
//随机不重复的6-8位
public static int card(){
int[] array = {0,1,2,3,4,5,6,7,8,9};
Random rand = new Random();
for (int i = 10; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}
int result = 0;
for(int i = 0; i < 6; i++){
result = result * 10 + array[i];
}
return result;
}
public static void main(String[] args) {
System.out.println(card());
}