开发者

Search algorithm - Java

I am finding it a little bit difficult to get a search algorithm to work properly in Java. Basically, the program has an array initialized. The user is supposed to enter a number via the keyboard, and Java will them print out the all the indexes where this number is found. My main problem lies in the fact that I want create a method which currently looks as follows:

    public static int[] linsearch(int[] numbers, int key) {
        int[] indexvalues = null;
        int n = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == key) {
                indexvalues[n] = i;
                n++;}
        }

        return indexvalues;
    }

The idea behind this is that given an array, and a number (in this case identified by "key"), the program will create a new array in which the indexes of where the number "key" is found in the original array will be saved. Currently I get this error message: java.lang.NullPointerException. I have tried different approaches to initializing this array, b开发者_高级运维ut none have been succesful so far. Thus, any help will be very appreciated!


The main difficulty stems from the fact that you don't know the size of the output array ahead of time. On the other hand, growing a Java array as needed is doable, but unpleasant.

There are several ways to fix this.

If I were you, I'd use a collection to store the indices:

public static Collection<Integer> linsearch(int[] numbers, int key) {
    ArrayList<Integer> indexvalues = new ArrayList<Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] == key) {
            indexvalues.add(i);
        }
    }
    return indexvalues;
}

You'll need to modify the calling code accordingly. I leave this as an exercise for the reader.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜