JAVA/ANDROID - 我怎样才能生成一个新的随机数,而不是与以前的随机数相同?

JAVA/ANDROID - How can I generate a NEW random number, without it being identical to the previous random number?

我正在用 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 命令做点什么,但我不确定。

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();
    }
}

// 主要 class

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

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

您可以拥有一个实用程序 class,它可以有一个唯一的号码生成器。像这样,

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



    }
}

老实说,如果你把它改成这样应该很简单:

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