Java 消除重复随机数
我需要以随机顺序获得数字0-11,并确保每个数字只获得一次。但它仍然在向我的Line2类发送相同的数字。如何确保int变量lineChoice每次都完全不同? 我的问题是if/else没有正确地确保我没有将已选择的lineChoice发送到我的Line2类Java 消除重复随机数,java,arrays,arraylist,random,Java,Arrays,Arraylist,Random,我需要以随机顺序获得数字0-11,并确保每个数字只获得一次。但它仍然在向我的Line2类发送相同的数字。如何确保int变量lineChoice每次都完全不同? 我的问题是if/else没有正确地确保我没有将已选择的lineChoice发送到我的Line2类 for(int i = 0; i < 12; i++){ //get a random line choice 0-11 lineChoice = (int)(Math.random() * 11); /
for(int i = 0; i < 12; i++){
//get a random line choice 0-11
lineChoice = (int)(Math.random() * 11); //0-11;
//if that number was already chosen
//get a new random number and add it to the array
if(randomNumbers.contains(lineChoice)){
lineChoice = (int)(Math.random() * 11); //0-11;
randomNumbers.add(lineChoice);
}else{
//if not already in array, add to array
randomNumbers.add(lineChoice);
}
//make a Line based on the random lineChoice number
line = new Line2(lineChoice);
//add the line to the string poem
poem += "\n" + line + "\n\n\n";
}
for(int i=0;i<12;i++){
//获得一个随机的行选择0-11
lineChoice=(int)(Math.random()*11);//0-11;
//如果已经选择了这个数字
//获取一个新的随机数并将其添加到数组中
if(randomNumbers.contains(lineChoice)){
lineChoice=(int)(Math.random()*11);//0-11;
随机数。添加(行选择);
}否则{
//如果尚未在数组中,请添加到数组
随机数。添加(行选择);
}
//根据随机lineChoice编号生成一行
line=新的Line2(lineChoice);
//把这一行添加到弦乐诗中
诗+=“\n”+行+”\n\n\n”;
}
您可以创建一个从1到11的整数列表,然后将其随机化
List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
Collections.shuffle(ints);
System.out.println(ints);
List ints=IntStream.range(1,12).boxed().collect(Collectors.toList());
集合。洗牌(整数);
系统输出打印项次(ints);
以下是推荐的方法
int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
System.out.println(nums[s]); // here is where you get your number
nums[s] = nums[i];
}
或者如果你只是想洗牌数组
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
int t = nums[s];
nums[s] = nums[i];
nums[i] = t;
}
您需要一个数组来执行此操作 按照下面的代码,您只需要总共生成11个(共12个)随机数。最后一个号码将自动选择
int[] rn = new int[12];
for(int i=0; i<12; i++) rn[i]=i; // 0 to 11
Random rNumber = new Random();
int t, z;
for(int i=11; i>0; i--) {
z = rNumber.nextInt(i+1);
t = rn[i];
rn[i] = rn[z];
rn[z] = t;
}
System.out.println(Arrays.toString(rn));
int[]rn=newint[12];
对于(int i=0;i0;i--){
z=RNNumber.nextInt(i+1);
t=rn[i];
rn[i]=rn[z];
rn[z]=t;
}
System.out.println(Arrays.toString(rn));