【发布时间】:2019-04-19 18:38:52
【问题描述】:
对你们来说可能是一项简单的任务,但我真的很难让它发挥作用。我正在创建一个可以返回 0-30 的随机整数的方法。但我想确保相同的数字不会被使用两次。因此,我创建了一个名为 UsedNumbersArray 的数组来跟踪所有内容。
我的想法是,它首先生成一个随机数,然后使用 for 循环逐个检查数组,看它是否存在。如果是这种情况,它必须用零替换该值,确保不会再次找到它。
但奇怪的是,它用我们的随机数替换了数组中的一个完全不同的数字。查看我的代码:
private static int checkIfNumberUsed(){
int questionNumber = randomNumberInRange(1,questionsWithAnswers[0].length); // create random number
boolean hasNotBeenUsed = false;
while (!hasNotBeenUsed){ // as long it HAS been used, it will continue to run the loop and create a random num till it gets what it wants
for (int i = 0; i < questionsWithAnswers[0].length ; i++) { // check if it has been used before
if (questionNumber==usedNumbersArray[i]){
usedNumbersArray[i]=0; // will replace the number with 0 so that it can't be found and used again
hasNotBeenUsed=true; // will exit the loop
}
}
questionNumber = randomNumberInRange(1,questionsWithAnswers[0].length); // if no matches are found it will generate a new random number
}
return questionNumber;
这是输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
8 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 0, 19, 20, 21, 22, 23, 24, 25 , 26, 27, 28, 29, 30]
如您所见。随机数是 8,但它用 0 代替了 18,而不是应该的 8?
希望你能解决这个问题。在此先感谢
【问题讨论】:
-
典型的做法是打乱数组并简单地迭代。您可能想尝试一下,因为它更简单。
-
另一种方法是填充数组(或列表),然后对其进行洗牌。每个请求都会将跟踪的索引移动到下一个元素。当索引达到数组的长度时,重置回0,并再次洗牌。
-
您的代码中发生的事情是第一次它会生成 18 它在数组中,所以它用 0 替换它 ..然后生成下一个随机数(在 while 循环结束时)如您在 outputpput 中看到的 8 。如果您想验证它,只需在生成后立即打印数字即可。
标签: java arrays random methods