试图找出 1-45 彩票抽奖中不会有任何连续数字的概率,无法弄清楚如何检查数字是否不是连续的,例如 8,9 或 15,14 任何人都可以帮忙;编辑。我更改了代码,现在它将值放入 int 数组中以对数字进行排序和比较,但现在每次都只输出零。
import java.util.Random;
public class Lotto {
Random rangen = new Random();
private int result;
public Lotto()
{
result = spin();
}
public int getSpin()
{
return spin();
}
private int spin()
{
return rangen.nextInt(45)+1;
}
} // this is my spin class with constructors
import java.util.Arrays;
public class con2
{
public static void main(String args[])
{
int num = 100;
int count = 0;
Lotto[] myarray = new Lotto[5]; //an array to hold the lotto spins
int[] numarray = new int[5];
for(int i=0; i<myarray.length; i++)//loop to go trough array
{
myarray[i] = new Lotto();//fill array with balls or spins
numarray[i] = myarray[i].getSpin();//fill int array with value of lotto spin
//Arrays.sort(myarray);//sort the array
}
Arrays.sort(numarray);//sort the number array
for(int i =0; i<num; i++)//monte carlo loop
{
for(int z=0;z<numarray.length*2;z++) //loop to go trough the array
{
if(numarray[z] == numarray[z+1])
{
count++;//here i want to add 1 to count if number is one larger than position at z
}
else if(numarray[z] == numarray[z-1])
{
count++;//here i want to add 1 to count if number is one less than position at z
}
else
{
break;//if numbers are the same break out of loop
}
}
}
System.out.println(count/num);
}
}
最佳答案
Spin方法应避免多次出现。乍一看应该改一下。您可以使用专门设置的集合。
关于java - 尝试求 1-45 抽奖中不出现任何连续号码的概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394920/