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

}
Maroun
  • 94,125
  • 30
  • 188
  • 241
mattersonline
  • 183
  • 1
  • 10

3 Answers3

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.

Smi
  • 13,850
  • 9
  • 56
  • 64
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++)
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
tarunajain
  • 89
  • 1
  • 3