Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();

}
share|improve this question

3 Answers

up vote 4 down vote accepted

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.

share|improve this answer
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++)
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.