【问题标题】:Looping and a boolean array?循环和布尔数组?
【发布时间】:2015-05-03 14:01:28
【问题描述】:

我正在上我的第一个 Java 编程课程,我目前正在尝试编写一个用户创建的方法,该方法将循环一个布尔数组,给我一个随机数,检查数组是否显示生成的数字是true 或 false,然后如果数组具有声明为 true 的生成数字的索引,则生成不同的数字(TL;DR:在布尔数组中查找随机索引,如果随机找到的数字为 true,则重新运行)。我目前的困境是,如果我使用 do/while 循环,如果数组的所有值都为真,则循环将永远不会停止,并且使用 if/else 只会重新运行该数字一次。我该如何解决这个问题?
编辑:到目前为止我的代码:

public static int getNextQuestion(boolean[] queue){
    int nextq = ((int)((11*Math.random())+1));
    if (queue [nextq]){
        int nextq = ((int)((11*Math.random())+1));  

【问题讨论】:

  • 告诉我们你到目前为止做了什么。
  • 随机数和布尔数组有什么关系?
  • 我正在尝试生成一个数字,该数字对应于数组中值为 false 的索引。 @SamTebbs33
  • public static void main(String[] args){ public static int getNextQuestion(boolean[] queue){ int nextq = ((int)((11*Math.random())+1) ); if (queue [nextq]){ int nextq = ((int)((11*Math.random())+1)); @ericbn
  • 好吧,您需要定义您的方法应该做什么,以防万一元素为真。无限循环,或者抛出异常,或者......我们无法决定您希望您的代码为您做什么。

标签: java arrays loops random


【解决方案1】:

在致电getNextQuestion() 之前,您似乎需要检查队列是否为真。然后我会使用递归,直到你生成一个错误。您可以跟踪调用递归方法的次数以查看它是否正常工作...

static Random rand = new Random();
static int recursiveCount = 0;

public static void main(String[] args) throws Exception {
    boolean[] queue = new boolean[] { true, false, true, true, false, true };
    if (checkIfAllTrue(queue) == false) {
        getNextQuestion(queue);
    }

    System.out.println("Recursive Count: " + recursiveCount);
    System.out.println("Done!");
}

public static void getNextQuestion(boolean[] queue) {
    recursiveCount++;

    int nextQ = rand.nextInt(queue.length);
    if (queue[nextQ]) {
        getNextQuestion(queue);
    }
}

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;
}

结果:

更新

在看到cmets关于返回随机错误索引的索引后,我更新了main()getNextQuestion()。其他一切都保持不变。

public static void main(String[] args) throws Exception {
    boolean[] queue = new boolean[]{true, false, true, true, false, true};
    if (checkIfAllTrue(queue) == false) {
        System.out.println("False index: " + getNextQuestion(queue));
    }

    System.out.println("Recursive Count: " + recursiveCount);
    System.out.println("Done!");
}

public static int getNextQuestion(boolean[] queue) {
    recursiveCount++;

    int nextQ = rand.nextInt(queue.length);
    if (queue[nextQ]) {
      return getNextQuestion(queue);
    } else {
        return nextQ;
    }  
}

结果:

【讨论】:

  • 谢谢!对此,我真的非常感激。 ^_^
【解决方案2】:

基本答案

正如@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;
}

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 2012-11-02
    • 2015-11-08
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多