英文:
Generate random and unique integer values
问题
我想创建一个方法,可以生成从0到999的随机且唯一的数字。我尝试过的方法是生成随机的唯一数字,然后将它们添加到一个向量中,这样每次调用该方法时,它都会生成一个随机数字,然后将其与先前生成的数字进行比较,看它是否是唯一的。如果不是,则重复这个过程。这是想法,但每次运行程序时,我都会得到"array index out of range: 0"的错误。
我在类的开头初始化了这个向量,如下所示:
private Vector<Integer> uniqueNums;
public int returnRandom() {
Random r = new Random();
int rand = r.nextInt(10000);
if (this.uniqueNums.capacity() != 0) {
for (int i = 0; i < this.uniqueNums.capacity(); i++) {
if (rand == this.uniqueNums.get(i))
returnRandom();
}
}
this.uniqueNums.add(rand);
return rand;
}
英文:
I want to create a method that will generate random and unique numbers from 0 to 999. What I've tried to do is to generate random unique numbers and then add them to a vector so that each time i call the method it will generate a random number and then compare it to the previously generated numbers and see if it's unique. If it's not, the process is repeated. Thats the idea but every time i run the program i get "array index out of range: 0".
I have initialized the vector at the beginning of the class as private Vector<Integer> uniqueNums;
public int returnRandom() {
Random r = new Random();
int rand = r.nextInt(10000);
if(this.uniqueNums.capacity() != 0) {
for(int i = 0; i < this.uniqueNums.capacity(); i++) {
if(rand == this.uniqueNums.get(i))
returnRandom();
}
}
this.uniqueNums.add(rand);
return rand;
}
答案1
得分: 1
看起来你已经声明了uniqueNums,但没有为其赋任何值。数组索引超出了null的范围。尝试将其初始化为一些空值,看看是否有所帮助。
不管怎样,这似乎是一种奇怪的创建“独特随机数”的方式。我会采纳dnault的建议。
英文:
It looks as if you have declared uniqueNums, but not assigned any value to it. The array index is out of range of a null. Try initializing it to some empty value and see if that helps.
Regardless, this seems like an odd way to create 'unique randoms'. I would go with dnault's suggestion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论