0

我想问一下如何在我的按钮中生成不重复的数字。我想生成一个不重复的数字,因为每当我运行我的项目时,它都会显示所有相同的数字。

下面是我的代码:

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]);

如果可能,我想知道如何设置不具有相同值的一、二和三按钮。

4

3 回答 3

3

您的代码几乎等同于:

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.
于 2013-08-27T16:15:04.557 回答
1

在android中,你可以生成一个这样的随机数。如果需要,您可以使用最小值和最大值来代替数组。

int min = 1;
int max = 10;
Random r = new Random();
int someRandomNo = r.nextInt(max - min + 1) + min;
one.setText(""+someRandomNo);

要仔细检查你没有得到相同的随机数,你只需要一些逻辑来检查它是否已经生成。您可以坚持使用您的阵列并在下次通话之前删除该号码。min或者,如果您使用and ,则在再次调用之前检查存储的整数max

于 2013-08-27T16:12:56.173 回答
0
private int previous = -1000; // Put a value outside your min and max

/**
 * min and max is the range inclusive
 */
public static int getRandomNumber(int min, int max) {

    int num;

    do {

        num = min + (int)(Math.random() * ((max - min) + 1));

    } while(previous == num); // Generate a number that is not the same as previous

    previous = num;

    return num;    
}
于 2013-08-27T16:21:46.013 回答