0

I'm getting a null pointer exception at line

if(names[j].compareTo(names[j+1]) > 0)

and I can't figure out why. It might have something to do with the initialization but I really don't know what it could be

public static void item3(Profitable[] movies, Scanner input) {
    int j;
    boolean flag = true;
    String temp;
    String search;
    int low = 0;
    int high;
    int mid;

    String[] names = new String[6];

    for(int i = 0; i < 5; i++) {
        names[i] = ((Movie)movies[i]).getTitle();
    }

    high = names.length - 1;
    mid = (low + high) / 2;

    while(flag)
    {
        flag = false;
        for(j = 0; j < names.length - 1; j++)
        {

            if(names[j].compareTo(names[j+1]) > 0) {
                temp = names[j];
                names[j] = names[j+1];
                names[j+1] = temp;
                flag = true;
            }
        }
    }

    System.out.print("Enter your search term: ");
    search = input.nextLine();

}
4

3 回答 3

4

This loop:

for(int i = 0; i < 5; i++) {
    names[i] = ((Movie)movies[i]).getTitle();
}

only initializes the first five elements, but the last one does not get initialized.

于 2013-03-30T19:21:35.263 回答
0
for(int i = 0; i < 5; i++) { // only 5 iterations while names contain 6 elements
    names[i] = ((Movie)movies[i]).getTitle();
}

It's always better to use i < names.length rather than an explicit integer.

for(int i = 0; i < names.length; i++)
于 2013-03-30T19:21:14.853 回答
0

You could also use i <= 5 but it's always better to use the length field.

于 2013-03-31T12:02:10.233 回答