Suggestions for my Selection Sort / Java

778 views Asked by At

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)
2

There are 2 answers

1
VD007 On BEST ANSWER

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.

1
Caleb Rush On

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