I am trying to print out a list of words from a given text, that will print it out in alphabetical order and then print out the frequencies of each word along side it.
I cannot it get to print out because I am getting this error:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1155)
at List.insert(Count2.java:101)
at Count2.main(Count2.java:17)
This is my code:
import java.util.Scanner;
public class Count2
{
static Scanner stdin = new Scanner(System.in);
public static void main(String[] args)
{
String word;
List sortedList = new List();
word = nextWord();
while(word != null)
{
sortedList.insert(word);
word = nextWord();
}
sortedList.print();
}
private static String nextWord()
{
if(stdin.hasNext())
{
String word = stdin.next();
word = word.toLowerCase();
int start = 0;
int end = word.length();
for(int c = 0; c < word.length(); ++c)
{
if(Character.isLetter(word.charAt(c)) || word.charAt(c) == '-')
{
start = c;
break;
}
}
for(int n = start; n < word.length(); ++n)
{
if(!(Character.isLetter(word.charAt(n)) || word.charAt(n) == '-'))
{
end = n;
break;
}
}
return word.substring(start,end);
}
else return null;
} // nextWord
} // end Count2
class List {
static class Node {
String word;
int count;
Node next;
Node(String word, Node next) {
word = word;
next = next;
count = 1; //the first time you add a word
}
}
private Node first;
private int numWords;
public List() { //make an empty list
first = null;
numWords = 0;
}
public void insert(String word)
{
if(first == null)
{
Node newNode;
newNode= addNode(word, null);
first = newNode;
}
else if (word.equals(first.word))
{
first.count++;
}
else
{
Node newNode;
Node current;
current = first;
Node previous;
previous = null;
int i = word.compareTo(current.word);
while((i > 0) && (current.next != null))
{
previous = current;
current = current.next;
i = word.compareTo(current.word);
}
if (( i > 0 && current.next == null))
{
newNode = addNode(word, null);
current.next = newNode;
}
else if ( i == 0)
{
current.count++;
}
else
{
newNode = addNode(word, current);
if( previous == null)
{
first = newNode;
}
else
{
previous.next = newNode;
}
}
}
}
private Node addNode(String word, Node next)
{
Node newNode = new Node(word, next);
numWords++;
return newNode;
}
public String[] getWords()
{
String[] WORDS = new String[numWords];
Node current = first;
int m = 0;
while( current != null)
{
WORDS[m] = current.word;
current = current.next;
m++;
}
return WORDS;
}
public int[] getNumbers()
{
int [] numbers = new int[numWords];
Node current = first;
int m = 0;
while(current != null)
{
numbers[m] = current.count;
current = current.next;
m++;
}
return numbers;
}
public void print()
{
int[] numbers = getNumbers();
String [] WORDS = getWords();
System.out.println("Word \t \t Occurs");
System.out.println("==== \t \t ======");
for( int i = 0; i < numWords; i++)
{
System.out.println(WORDS[i] + " \t " + numbers[i]);
}
}
}