我在解決如何讓程序在Java中工作時遇到一些問題。我應該有一個類單詞表:將字符串插入排序數組
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
而且我們應該有兩個構造函數: 第一種:
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
}
第二個:
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)
}
}
最後一個插入方法。我認爲主要問題在這裏。我不知道如果我的兩個構造是正確的,但我110%肯定有什麼東西錯在這裏:
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
}
}
從本質上講它應該插入提供到字的已排序數組的字,並保持列表排序。該程序只是崩潰。任何想法可能是錯誤的?
'NullPointerException' ???????? – Biu 2015-01-21 01:21:04