I'm having some problems figuring out how to do get this program to work in Java. I'm supposed to have a class WordList:
public class WordList{
private int size; //number of words in array
private String array1[]; //array of words
private int capacity; // how big the array is supposed to be
And we're supposed to have two constructors: First one:
public WordList(int capacity){
this.array1 = new String[capacity]; //makes a new array of specified capacity
this.capacity = capacity; //sets the capacity
this.size = 0; //sets the size of array (i.e. # of words) to 0
}
Second one:
public WordList (String[] arrayOfWords){
this.capacity = 2 * arrayOfWords.length; //makes the capacity of array twice the # of words in input array
this.array1 = new String[capacity]; //makes a new array
this.size = arrayOfWords.length; //sets the # of words in array
for (int i = 0; i < arrayOfWords.length; i++){ //loops through array
this.insert(arrayOfWords[i]); //inserts the words (sorted into our array)
}
}
and finally an insert method. I think the main problem is here. I don't know if my two constructors are correct, but I'm 110% sure there's something wrong here:
public void insert(String newword){
for (int i = 0; i < size; i++){
int l = newword.compareTo(array1[i]);
if (l > 0)
continue; // means that the word we're inserting is after
if (l < 0){
for (int j = size; j > i; j--){
array1[j] = array1[j-1]; //shifts all array elements over by one - starting at end of array to avoid over writing anything
}
array1[i] = newword;//inserts the word
}
if (l == 0)
return;//doesn't do anything if word is already in list
}
}
Essentially it's supposed to insert the word provided into an already sorted array of words and keep the list sorted. The program just crashes. Any ideas on what might be wrong?
NullPointerException????????