3

I'm new to programming/coding and have been stuck on a project in school for a few days now. The goal is to take an array full of words (each position is a different word) and sort it alphabetically. I've tried doing some research on stack overflow already, but I'm having a bit of trouble following some of the examples I've found. The class and driver (I'm using a two part setup if you will) both compile fine, no problems there. The problem occurs when I try to use alphaSort from my driver. I receive a null pointer exception for the line marked below. I've had some trouble with these exceptions in the past, so I'm sure it's something small I'm overlooking. As stated however, I'm not yet fluent enough in the java syntax to catch a small error like that.

I figured I should just include the entire method in-case my error is something in the beginning, before the sorting part. What I have so far (i found this on Stack overflow):

public void alphaSort()
{
    String alphaList[] = new String[wordList.size()];
    int count=0;
    //puts wordList into alphaList for easier sorting
    while(count<wordList.size()-1)
    {
        alphaList[count]=wordList.get(count);
        count++;
    }
    int shortestStringIndex;
    //sort begins here
    for(int j=0; j<alphaList.length -1; j++)
    {
        shortestStringIndex = j;
        for(int i=j+1; i<alphaList.length; i++)
        {
            if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
            {
                shortestStringIndex = i;
            }
        }
        if(shortestStringIndex !=j)
        {
            String temp = alphaList[j];
            alphaList[j] = alphaList[shortestStringIndex];
            alphaList[shortestStringIndex]=temp;
        }
    }
    //prints out results
    count=0;
    while(count<alphaList.length)
    {
        System.out.println(alphaList[count]);
        alphaOut.print(alphaList[count]);
        count++;
    }
}

Any help would be greatly appreciated. Please be as thorough as possible in giving an answer (as i said, I'm a bit of a java newbie). Thanks :)

edit: to test for null values (which i assume are spots in my array list that are blank) i made the following method:

    public void isNull()
{
    int count=0;
    while(count<wordList.size()-1)
    {
        if((wordList.get(count)).equals(""))
        {
            System.out.println("null");
            break;
        }
        else
        {
            System.out.println("nothing yet");
        }
        count++;
    }
}

the while loop never broke early, my method ran to completion.

4
  • fun way to learn.. sorting-algorithms.com Commented Dec 14, 2015 at 4:26
  • One very useful thing in debugging these kinds of problems is the stack-trace that you get in the console when the error occurs. It'll usually say NullPointerException, and give you a line number where the error occurred. If you look at your code and the line number it mentions, there are usually only one or two variables in play there, and then you can reason out which one is null, and why that happened. Commented Dec 14, 2015 at 4:27
  • A blank string isn't the same as null. A null reference would be a variable that doesn't contain a string value at all. e.g. String a = null. To test isNull, simply say if (string == null). Commented Dec 14, 2015 at 4:44
  • thanks. didn't know this. Commented Dec 14, 2015 at 4:48

5 Answers 5

3

You need to update the first while loop to match:

while(count < wordList.size()) {
            alphaList[count] = wordList.get(count);
            count++;
        }

You aren't copying over every index of the list to the array, which means that when it goes to check the last index, it cannot find a value (NullPointerException).

Edit:

Here's my full test class that works:

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    private ArrayList<String> wordList = new ArrayList<String>();

    public Test() {
        wordList.add("Test");
        wordList.add("Bee");
        wordList.add("Pig");
        wordList.add("Dog");
        alphaSort();
    }

    public void alphaSort() {
        String[] alphaList = new String[wordList.size()];
        int count = 0;
        while(count < wordList.size()) {
            alphaList[count] = wordList.get(count);
            count++;
        }
        int shortestStringIndex;
        for(int j = 0; j < alphaList.length - 1; j++) {
            shortestStringIndex = j;
            for(int i = j + 1; i < alphaList.length; i++) {
                if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim()) < 0) {
                    shortestStringIndex = i;
                }
            }
            if(shortestStringIndex != j) {
                String temp = alphaList[j];
                alphaList[j] = alphaList[shortestStringIndex];
                alphaList[shortestStringIndex]= temp;
            }
        }
        count = 0;
        while(count < alphaList.length) {
            System.out.println(alphaList[count++]);
        }
    }

}

Output:

Bee
Dog
Pig
Test
Sign up to request clarification or add additional context in comments.

4 Comments

this works. I'm still having errors, but i tested only your inputs (test, bee, ect) and it worked just fine. this leaves me to assume it's a null value in my array list. I'll work on solving that tomorrow i guess. Do you have any easy way of removing a null value from an array list?
@corvonik Do this before running alphaSort wordList.removeAll(Collections.singleton(null));
looks perfect. what do i have to import to use Collections? compiled and recieved error: could not find symbol
import java.util.Collections;
1

Try this...

 // sorting array
 if(wordList.size()>0){
   String alphaList[] = new String[wordList.size()];
   //convert list to String array
   alphaList= wordList.toArray(alphaList);
   //sorting
   Arrays.sort(alphaList);
 }

 ........

// let us print all the elements available in wordList
 if(wordList.size()>0){
   for (String word: alphaList) {
   System.out.println("word= " + word);
  }
 }

Comments

1

There is an error when you are copying your List to an array. It is inserting a null at the end of the list which is causing your NullPointerException. Here is the revised version that works. Instead of looping through the List and copying each item to the array(which is buggy) I just use the standard java method that is on a List to convert the List to an array.

public static void alphaSort()
{
    String alphaList[] = wordList.toArray(new String[]{});
    int shortestStringIndex;
    //sort begins here
    for(int j=0; j<alphaList.length -1; j++)
    {
        shortestStringIndex = j;
        for(int i=j+1; i<alphaList.length; i++)
        {
            if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
            {
                shortestStringIndex = i;
            }
        }
        if(shortestStringIndex !=j)
        {
            String temp = alphaList[j];
            alphaList[j] = alphaList[shortestStringIndex];
            alphaList[shortestStringIndex]=temp;
        }
    }
    //prints out results
    int count=0;
    while(count<alphaList.length)
    {
        System.out.println(alphaList[count]);
        alphaOut.print(alphaList[count]);
        count++;
    }
}

5 Comments

tried this. I love that it makes the transfer easier, but i'm still getting the null pointer exception
Make sure you aren't inserting a null into the wordList. You haven't posted your full code so I can't verify what is happening to wordList outside of this method.
I copied your code in and ran it but I had to create my own wordList. When I did that it worked. I can post my full code if you think it would help you.
it's my word list then. working on removing the null right now. thanks for all the help mate.
No problem. Please don't forget to accept my answer if it helped you solve the problem. Thanks!
0

The problem is that you're adding wordList.size()-1 number of items into the array and the array size is wordList.size() which means that the last value in the array is null

3 Comments

I thought this was the problem early on. Tried it again just to double check. no such luck :/
Are you certain that there are no null values in wordList?
@corvonik If this wasn't the only problem, maybe the wordList list contains null values.
0

For this while loop:

while (count<wordList.size()-1)
{
    alphaList[count]=wordList.get(count);
    count++;
}

you don't need to loop to wordList.size()-1 since you already do < instead of <=. You are stopping your loop at the second to last index and are thus not assigning a value to the last place in the array. Instead do while (count < wordList.size()) or while (count <= wordList.size()-1)

1 Comment

I thought this was the problem early on. Tried it again just to double check. no such luck :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.