我想问如何在我的按钮中生成不重复的数字。我想生成一个不重复的数字,因为每当我运行我的项目时,它都会显示所有相同的数字。
下面是我的代码:
int arr1[]={1,2,3,4,5,6,7,8,9,10};
int num=(int)(Math.random()*10);
one.setText(""+arr1[num]);
two.setText(""+arr1[num]);
three.setText(""+arr1[num]);
我想知道如何设置一、二、三按钮如果可能的话不具有相同的值。
最佳答案
您的代码几乎等同于:
int arr1[]={1,2,3,4,5,6,7,8,9,10};
int num = arr1[(int)(Math.random()*10)];
one.setText(""+num);
two.setText(""+num);
three.setText(""+num);
这就是为什么您会看到相同数字的 3 倍。
您应该使用Random#nextInt(int n)而不是你的数组并生成 3 个随机数:
Random r = new Random();
one.setText(Integer.toString(1 + r.nextInt(10)));
two.setText(Integer.toString(1 + r.nextInt(10)));
three.setText(Integer.toString(1 + r.nextInt(10)));
如果您希望数字不重复,您可以使用 Set 等:
Random r = new Random();
Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() <= 3){
//If the new integer is contained in the set, it will not be duplicated.
randomNumbers.add(1 + r.nextInt(10));
}
//Now, randomNumbers contains 3 differents numbers.
关于java - 在android中处理随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470579/