java-重复的号码检查并不总是有效
作者:互联网
我有一个函数getNormalList(),该函数必须返回带有3个随机整数0-5的列表,但并不完全相同.它没有像我希望的那样工作.有时,尽管进行了检查,但仍输出相同的3个数字.
public class SpinResultGenerator {
public ArrayList<Integer> getNormalList() {
ArrayList<Integer> integerList = new ArrayList<Integer>();
Random r = new Random();
int Low = 0;
int High = 6;
for (int i = 0; i < 3; i++) {
int number = r.nextInt(High - Low) + Low;
integerList.add(number);
}
if (integerList.get(0) == integerList.get(1) && integerList.get(0) == integerList.get(2)
&& integerList.get(1) == integerList.get(2)) {
integerList.clear();
for (int i = 0; i < 3; i++) {
int number = r.nextInt(High - Low) + Low;
integerList.add(number);
}
}
return integerList;
}
public ArrayList<Integer> getJackpotList() {
ArrayList<Integer> integerList = new ArrayList<Integer>();
integerList.add(5);
integerList.add(5);
integerList.add(5);
return integerList;
}
}
例如,如果结果为[4,4,4],则for循环将生成新数字.但是它仍然能够输出3个相同的整数.为什么?
解决方法:
您需要一个嵌套循环.您的for循环应重复进行,直到找到3个可接受的数字为止.我使用数组使代码更紧凑,但是使用ArrayList也可以做到这一点.
public List<Integer> getNormalList() {
Random r = new Random();
int[] arr = new int[3]; // initialized to 0s by default
int Low = 0;
int High = 6;
while (arr[0] == arr[1] && arr[1] == arr[2]) { // will repeat as long as the 3 number as
// all equal
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(High - Low) + Low;
}
}
return Arrays.asList(arr);
}
标签:if-statement,for-loop,random,java 来源: https://codeday.me/bug/20191109/2010670.html