首先,我是一名新手 Android App 开发人员。在我的应用程序中,我需要一个在给定范围内生成随机数以避免重复的类。我已经为这个问题搜索了很多,但我还没有找到任何适合我的案例的具体解决方案。好吧,我以为我找到了一个我稍微重新适应的,但它不能正常工作。代码如下:
public class NoRepeatRandom {
private int[] number = null;
private int N = -1;
private int size = 0;
public NoRepeatRandom(int minVal, int maxVal)
{
N = (maxVal - minVal) + 1;
number = new int[N];
int n = minVal;
for(int i = 0; i < N; i++)
number[i] = n++;
size = N;
}
public void Reset() { size = N; }
// Returns -1 if none left
public int GetRandom()
{
if(size <= 0) return -1;
int index = size * (int)Math.random();
int randNum = number[index];
// Swap current value with current last, so we don't actually
// have to remove anything, and our list still contains everything
// if we want to reset
number[index] = number[size-1];
number[--size] = randNum;
return randNum;
}
}
当我调用 GetRandom() 时,我没有达到预期的结果,因为它总是返回给定范围的最小数量。例如:
NoRepeatRandom nrr = new NoRepeatRandom(0, 10);
int yes = nrr.GetRandom();
//Here I create a Toast just to see the numbers that the method is returning.
Toast toast = Toast.makeText(MainActivity.this, Integer.toString(yes), Toast.LENGTH_SHORT);
toast.show();
结果是:0,0,0,0,0,0.... 对于范围 (5,10),结果是 5,5,5,5....
有人知道代码有什么问题吗?我真的很感激任何帮助!
先感谢您。