-2

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.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
zlavy
  • 3
  • 5
  • @Marvin I've looked at that post and it really didn't fully look at my situation and I could not understand it completely. – zlavy Jan 24 '17 at 15:31
  • Which line is BubbleSort.java:48? You have a NPE on that line. – Steve Smith Jan 24 '17 at 15:41
  • @student100 You could run the loop till the `a` variable which you have passed, which would eliminate the possibility of getting a null value from the `array` as explained by Anton in his answer. – dumbPotato21 Jan 24 '17 at 15:48

4 Answers4

2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

I guess String[] name = new String[30]; contains null elements. In your example there are only 8 strings

Bob Flower

Tina Sea

Krusty Crab

Mark Klutz

However you create an array with 30 elements. As result there will be 8 String objects in the array and 22 null. And later on in array[j].compareTo(array[j + 1]) there is comparison between a valid String object and null. Try to use ArrayList instead of String[].

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
0

You have problem with allocating memory(array) and using calculated indeces to access element. As a result you have a problem accessing not initialized elements or another time you could get IndexOutOfBoundExceptions. As a beginner it might helpful to learn and do it in low level, but I would like to share a little for your interest, and also it may help not to hate Java.

File class is old, try to use NIO.2 which came with Java 7.

For higher level abstraction here is a one line sorting solution:

Files.readAllLines(Paths.get("names.txt"))
     .stream().filter(p -> p.length() > 0)
     .forEachOrdered(System.out::println);

It could be even tried out in JShell(Java 9).

Files.readAllLines(Paths.get("names.txt"))
     .stream().filter(p -> p.length() > 0)
     .sorted()
     .toArray(String[]::new);

Output:

{ "Bob Flower", "Krusty Crab", "Mark Klutz", "Tina Sea" }
selimssevgi
  • 196
  • 5
-1

Nope - You're accessing a null array element past the size of your array length. When you're at the end and access array[j + 1], it's null.

      if (array[j].compareTo(array[j + 1]) > 0) { <- culprit here
older coder
  • 614
  • 1
  • 4
  • 12