Search code examples
javaarraysfilebubble-sort

Taking in a File and Alphabetizing it in Java: NullPointer Exception


I am trying to read in a file and alphabetize the names. The file has a list of first and last names, for example:

Bob Flower
Tina Sea
Krusty Crab
Mark Klutz

I want to use bubble sort to alphabetize the strings. I keep getting an error saying:

java.lang.NullPointerException
    at java.lang.String.compareTo(Unknown Source)
    at BubbleSort.Alphabetize(BubbleSort.java:48)
    at BubbleSort.main(BubbleSort.java:31)

My Code so far is:

import java.util.*;
import java.io.*;

public class BubbleSort
{
    public static void main(String[] args)
        throws IOException
    {
        File inData = new File("names.txt");
        if (!inData.exists()) {
            System.out.println("File does not exist");
            System.exit(0);
        }

        Scanner input = new Scanner(inData);
        int x = 0;
        String[] name = new String[30];
        //String[] extra = new String[30];

        while (input.hasNext()) {
            name[x] = input.next();
            input.nextLine();

            // extra[x] = input.next();
            // System.out.println(name[x]);
            x++;
        }

        BubbleSort sorter = new BubbleSort();
        sorter.Alphabetize(name, x);

        for (int i = 0; i < x; i++) {
            System.out.println(name[i]);
        }
        input.close();
    }

    private static void Alphabetize(String[] array, int a)
        throws IOException
    {
        String temp;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j].compareTo(array[j + 1]) > 0) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
}

I don't understand how to fix this error, or what is truly wrong.


Solution

  • You're sorting an unused (and therefore null) array element. Instead of array.length you should be using a, throughout the sort method. That's what a is for.