基本答案
正如@Shar1er80 所述,您需要检查所有元素是否为真之前 遍历您的数组。这是使用循环(迭代,非递归)和Math.random()的解决方案
public static void main(String[] args) {
boolean[] array = new boolean[] { true, false, true, true, false, true };
int iterationNumber = 0;
int nextItem;
if (checkIfAllTrue(array) == false) {
boolean retry;
do {
nextItem = generateRandomInt(array.length);
retry = array[nextItem];
iterationNumber++;
} while (retry == true);
System.out.println("The false is found at index " + nextItem);
}
System.out.println("iterationNumber = " + iterationNumber);
}
/**
* Checks if all the elements of the given boolean array are true.
* @param queue The boolean array to check.
* @return True if all elements are true, false if at least an element is false.
*/
public static boolean checkIfAllTrue(boolean[] queue) {
// Check your queue for all trues before proceeding
boolean allTrue = true;
for (int i = 0; i < queue.length; i++) {
if (queue[i] == false) {
allTrue = false;
break;
}
}
return allTrue;
}
/**
* Generates an int between 0 included and range excluded.
* @param range The maximum value of the range (excluded from generation).
* @return An integer between 0 included and range excluded.
*/
public static int generateRandomInt(int range) {
return (int) (Math.random() * range);
}
代码改进
鉴于这是您的第一门 Java 课程,上面的代码很冗长。前两种方法可以简化,以考虑到
boolean b;
// Code that initiates b
if (b == true) {
// Code here...
}
等价于
boolean b;
// Code that initiates b
if (b) {
// Code here...
}
您可以使用 foreach 循环遍历数组(请参阅http://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html)。
所以你可以有更愉快的阅读(最后一种方法保持不变):
public static void main(String[] args) {
boolean[] array = new boolean[] { true, false, true, true, false, true };
int iterationNumber = 0;
int nextItem;
if (!checkIfAllTrue(array)) {
boolean retry;
do {
nextItem = generateRandomInt(array.length);
retry = array[nextItem];
iterationNumber++;
System.out.println("nextItem = " + nextItem);
System.out.println("retry = " + retry);
System.out.println("iterationNumber = " + iterationNumber);
} while (retry);
System.out.println("The false is found at index " + nextItem);
}
System.out.println("iterationNumber = " + iterationNumber);
}
public static boolean checkIfAllTrue(boolean[] queue) {
// Check your queue for all trues before proceeding
boolean allTrue = true;
for (boolean element : queue) {
if (!element) {
allTrue = false;
break;
}
}
return allTrue;
}