【问题标题】:Divide and conquer algorithm - result NullPointerException分而治之算法 - 结果 NullPointerException
【发布时间】:2019-06-03 07:34:21
【问题描述】:

我正在做一个使用分治法的程序。不幸的是,我不能使用find(...) 方法。 我不知道在这一行中该做什么而不是 null:find(null, 0, 100, 34)。 提前谢谢你。

public class Main {
    static int find (double T[], int left, int right, double numToSearch) {
        if (left <= right) {
            int middle = (left + right) / 2;
            if (T[middle] == numToSearch) {
                return middle;
            }
            if (T[middle] < numToSearch) {
                return find(T, middle+1, right, numToSearch);
            }
            return find(T, left, middle-1, numToSearch);
        }
        return -1;      
    }

    public static void main(String[] args) {
        System.out.println(find(null /* (OR WHAT HERE TO MAKE IT WORK) */, 0, 100, 34));
    }

【问题讨论】:

  • 您要在哪个数组中查找数字?
  • 很遗憾,我不能使用“find”方法 - 你知道这是在调用find 方法 -> System.out.println(find(null /* (OR WHAT HERE TO MAKE IT WORK) */, 0, 100, 34));
  • 问问自己:我想从哪个数组中找到34

标签: java divide-and-conquer


【解决方案1】:

您必须提供一个数组,double[]。另外,你必须调用find(...)方法,使用这个数组作为第一个参数和一个有效的第三个参数(`right``不能大于数组的最大索引)。 p>

查看这段代码,它基本上是您的代码加上一个示例数组、对find 方法的正确调用以及main 方法中的一些(希望有帮助)cmets:

public class Main {

    static int find(double T[], int left, int right, double numToSearch) {
        if (left <= right) {
            int middle = (left + right) / 2;
            if (T[middle] == numToSearch) {
                return middle;
            }
            if (T[middle] < numToSearch) {
                return find(T, middle + 1, right, numToSearch);
            }
            return find(T, left, middle - 1, numToSearch);
        }
        return -1;
    }

    public static void main(String[] args) {
        // create an array that you can use for searching a number, here it is 34 at index 8
        double[] array = {1, 2, 3, 4, 5, 6, 7, 30, 34, 44, 45, 66, 67, 71, 72, 73, 77, 85, 89, 90, 99};
        // use the find-method with a valid maximum index (right) and the array defined before
        System.out.println(find(array, 0, array.length - 1, 34));
    }

}

结果只有 8,所以可能会在输出中添加更多信息,如下所示:

public static void main(String[] args) {
    // create an array that you can use for searching a number, here it is 34 at index 8
    double[] array = {1, 2, 3, 4, 5, 6, 7, 30, 34, 44, 45, 66, 67, 71, 72, 73, 77, 85, 89, 90, 99};
    double numberToFind = 34;
    // use the find-method with a valid maximum index (right) and the array defined before
    System.out.println("The number " + numberToFind + " is at index " + find(array, 0, array.length - 1, 34));
}

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2012-01-01
    • 2013-02-03
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多