1

My Selection Sort algorithm is not working. I am getting the following errors: //Exception in thread "main" java.lang.NullPointerException

Note: this is for a java class. I do not have a lot of experience. I am done with the assignment. I am trying to understand the reason why my sorting algorithm isn't working. Any suggestions on how to correct the problem? Tips? Corrections? ... any help at all will be appreciated. Here is my code:

    private void sortFlowers(String flowerPack[]) {
        // TODO: Sort the flowers in the pack (No need to display them here) - Use Selection or Insertion sorts
        // NOTE: Special care is needed when dealing with strings! research the compareTo() method with strings


         for(int i = 0; i < flowerPack.length; i++){         
         String currentMinFlow = flowerPack[i];
         int minIndex = i;

            for(int j = i; j < flowerPack.length; j++){
               if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){ 
                  currentMinFlow = flowerPack[j];
                     minIndex = j;
                  }
               }


               if(minIndex != i){
                  flowerPack[minIndex] = flowerPack[i];
                  flowerPack[i] = currentMinFlow;
               }
            }
        }

Exception:

Exception in thread "main" java.lang.NullPointerException at
    java.lang.String$CaseInsensitiveComparator.compare(String.java:1181) at 
    java.lang.String$CaseInsensitiveComparator.compare(String.java:1174) at 
    java.lang.String.compareToIgnoreCase(String.java:1227) at 
    Assignment01Driver.sortFlowers(Assignment01Driver.java:112) at 
    Assignment01Driver.<init>(Assignment01Driver.java:37) at 
    Assignment01Driver.main(Assignment01Driver.java:5)
sag_dc
  • 99
  • 1
  • 10
  • 1
    Look at the full stack trace when the program crashes. It will point you to a line with an uninitialized reference. – Ellen Spertus Jun 10 '15 at 01:02
  • Exception in thread "main" java.lang.NullPointerException at java.lang.String$CaseInsensitiveComparator.compare(String.java:1181) at java.lang.String$CaseInsensitiveComparator.compare(String.java:1174) at java.lang.String.compareToIgnoreCase(String.java:1227) at Assignment01Driver.sortFlowers(Assignment01Driver.java:112) at Assignment01Driver.(Assignment01Driver.java:37) at Assignment01Driver.main(Assignment01Driver.java:5) – sag_dc Jun 10 '15 at 01:03
  • This is what I get -I am not sure what it means. – sag_dc Jun 10 '15 at 01:04
  • Include the stack trace in your question. The error is on line 112. I see that from the stack trace. – Ellen Spertus Jun 10 '15 at 01:06
  • @d_PI: Seems like the `sort` method is wrong. Since, say you have added only a single flower to the array, but the sort method is still trying to sort the whole list of `25` flowers, when it should be concerned about sorting only a single flower, since actually the list has only one flower, though no doubt, it can hold another `24`. But sorting should be performed on the current content, instead of the whole list. Hence both the loops inside sort method, should use somethingy like `for ( int i = 0; i < numberOfFlowersAtPresent; ++i)` and likewise for the second loop. – nIcE cOw Jun 10 '15 at 01:07
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – almightyGOSU Jun 10 '15 at 01:07
  • Perhaps, you could check first in your sort function if `currentMinFlow ` is null or not. If it's null, don't compare, else do it. – mr5 Jun 10 '15 at 01:16
  • @nIcEcOw what you're saying makes sense. I have to figure out how to fix it. My professor has seen this code four time and she keeps making suggestions to fix it, yet none of them work. – sag_dc Jun 10 '15 at 02:24

2 Answers2

1

The issue is coming from the fact that your array was created with a fixed size.

 String[] flowerPack = new String[25];

When you create an array of reference type variables, each variable will be initialized with a value of null. If you call the sortFlowers method before each variable is given a value, you run into an issue.

for(int i = 0; i < flowerPack.length; i++){         
     String currentMinFlow = flowerPack[i];

In the above segment, you are iterating through all 25 positions in the array, including the values that still have a value of null. Then, the following line causes the error:

if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){ 

Since you are iterating through the entire array, you end up with values of currentMinFlow that are null. If you try to make a method call on a null reference value, you end up with a NullPointerException.

Generally, you rarely want to use fixed size arrays when you're unsure of how many data items you're likely to have. In this case, you would want to use an ArrayList in place of a standard array. An ArrayList is essentially a dynamic array that grows and shrinks as necessary to contain the elements you store in it. This will get rid of your problem with null values, since this will prevent you from having any unused elements in your array.

Replace

String[] flowerPack = new String[25];

with

ArrayList<String> flowerPack = new ArrayList<>();

If you wanted to add or remove a value from the ArrayList you could do

// Add value.
flowerPack.add(value);
// Remove value
flowerPack.remove(value);

If you want to access a certain element in the ArrayList:

String element = flowerPack.get(indexOfElement);

If you want to get the size of the ArrayList:

int size = flowerPack.size();

And if you don't want to modify your sorting method, you can keep it the same by replacing the line

sortFlowers(flowerPack);

with

sortFlowers(flowerPack.toArray(new String[0]));

For an overview of other ArrayList methods and properties, check the online documentation: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Caleb Rush
  • 512
  • 4
  • 7
0

The error says that you are trying to deal with the array that holds a value of null. to understand better, fill in all 25 spots in the array and run the program, it will not give you any error.

Here is the solution that you need.

private void sortFlowers(String flowerPack[])
{
    //get the length of the array by counting arrays where the value is not null.
    int length = 0;
    for (int i = 0; i < flowerPack.length; i++)
    {
        if (flowerPack[i] != null)
        {
             length = length + 1;
        }
    }

    //just confirm that the count is correct.
    System.out.println(length);

    //set the length to the "length" variable as we have found above.
    for(int i = 0; i < length; i++)
    {         
        String currentMinFlow = flowerPack[i];
        int minIndex = i;
        for(int j = i; j < length;j++){
            if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0)
            { 
                currentMinFlow = flowerPack[j];
                minIndex = j;
            }
        }
        if(minIndex != i){
            flowerPack[minIndex] = flowerPack[i];            
            flowerPack[i] = currentMinFlow;
        }
    }
}

Just replace your sortFlowers method with above code and check.

VD007
  • 267
  • 2
  • 15