JAVA / ANDROID - 如何在不与之前的随机数相同的情况下生成新的随机数?

时间:2015-03-07 09:47:53

标签: java android random numbers

我使用Random random = new Random();生成2个随机数来进行随机求和。代码:

    int min = 5, max = 20
    randomNum = random.nextInt((max - min) + 1) + min;
    randomNum1 = random.nextInt((max - min) + 1) + min;

然后我显示这样的总和:

    TextView sumText = (TextView) findViewById(R.id.sumText);
    sumText.setText(randomNum + " + " + randomNum1 + " =");

总和低于EditText,然后当我输入答案时,它会检查答案是否合适,当它好时,它会重复上面的所有代码,以便生成新的总和。 但是,我还是有问题。有时,当生成总和时,它会生成与旧总和相同的总和。如何让它产生一个新的总和,而不是与之前的总和相同?我想我应该对while命令做点什么,但我不确定。

3 个答案:

答案 0 :(得分:2)

public class Test {

    Random random;
    private int min = 5, max = 20;

    int num1;
    int num2;

    public Test(){
        random = new Random();
        num1 = random.nextInt((max - min) + 1) + min;
        num2 = random.nextInt((max - min) + 1) + min;
    }

    public int getSum(){
        return num1 + num2;
    }

    @Override
    public boolean equals(Test obj) {
        return this.getSum() == obj.getSum();
    }
}

//主要课程

Test t1 = new Test();
Test t2 = new Test();

while(t2.equals(t1)){
    t2 = new Test();
}

答案 1 :(得分:0)

您可以拥有一个实用程序类,它可以具有唯一的数字生成器。像这样,

import java.util.*;
import java.lang.*;
import java.io.*;

class RandomNumberGenerator
{
    private int min = 5, max = 20;
    private List<Integer> randomList = new ArrayList<Integer>();

    private Random random = new Random();

    public int getNextRandomNumber() {

        int randomNum = random.nextInt((max - min) + 1) + min;
        if(randomList.contains(randomNum)) {
            randomNum = getNextRandomNumber();
        }
        randomList.add(randomNum);
        return randomNum;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        // you can use this piece of code anywhere to generate 
        // random numbers using the utility method of RandomNumberGenerator

        RandomNumberGenerator randomNumberGenerator = new RandomNumberGenerator();
        int randomNum = randomNumberGenerator.getNextRandomNumber();
        int randomNum1 = randomNumberGenerator.getNextRandomNumber();

        System.out.println(randomNum);
        System.out.println(randomNum1);



    }
}

答案 2 :(得分:0)

如果你只是改变它,说实话应该很简单:

int min = 5, max = 20;
randomNum = random.nextInt((max - min) + 1) + min;
do {
    randomNum1 = random.nextInt((max - min) + 1) + min;
} while(randomNum == randomNum1);

编辑:您只需要存储以前的金额。

List<Integer> sums = new ArrayList<Integer>();
randomNum = random.nextInt((max - min) + 1) + min;
do {
    randomNum1 = random.nextInt((max - min) + 1) + min;
} while(sums.contains(randomNum+randomNum1));
sums.add(randomNum + randomNum1);