方法一:
import java.util.Random;
public class Demo01 {
public static void main(String[] args) {
Random random = new Random();
int code = random.nextInt(9000) + 1000;
System.out.println(code);
}
}
方法二:
import java.util.UUID;
public class Demo02 {
public static void main(String[] args) {
String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
System.out.println(uuid);
}
}
方法三:
public class Demo03 {
public static void main(String[] args) {
int[] array=new int[4];
for (int i = 0; i < 4; i++) {
array[i]=(int)(Math.random()*10);
for(int j=0;j<i;j++){
if(array[i]==array[j]){
i--;
}
}
}
for (int i = 0; i < 4; i++) {
System.out.print(array[i]);
}
}
}
方式四:
import java.util.Random;
public class Demo04 {
public static void main(String[] args) {
//定义一个字符串(A-Z,a-z,0-9),一共62为
String str="abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//由Random生成随机数
Random random=new Random();
StringBuffer sb=new StringBuffer();
//长度为几就循环几次
for (int i = 0; i <4 ; i++) {
//产生0-61的数字
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
System.out.println(sb.toString());
}
}
方式五:
public class Demo5 {
public static void main(String[] args) {
String str="ABCDEF0123456789";
char[] chars = str.toCharArray();
StringBuffer sb=new StringBuffer();
for (int i = 0; i <4 ; i++) {
int index=(int)(Math.random()*chars.length);
sb.append(chars[index]);
}
System.out.println(sb.toString());
}
}
方式六:
import java.util.HashSet;
import java.util.Set;
public class Demo6 {
public static void main(String[] args) {
Set<Integer> set=new HashSet<Integer>();
int code;
while (set.size()<4){
code=(int)(Math.random()*10000);
set.add(code);
}
for (Integer i:set) {
System.out.println(i);
}
}
}
文章来源地址https://www.toymoban.com/news/detail-533341.html
文章来源:https://www.toymoban.com/news/detail-533341.html
到了这里,关于java生成4位不重复的随机数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!