2015-01-21 104 views
1

我在解決如何讓程序在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 
    } 
    } 

從本質上講它應該插入提供到字的已排序數組的字,並保持列表排序。該程序只是崩潰。任何想法可能是錯誤的?

+0

'NullPointerException' ???????? – Biu 2015-01-21 01:21:04

回答

0

這功課嗎?我想是的,所以我只會提出一些想法,而不是完整的答案。

  1. 由於數組排序,你可以使用Arrays.binarySearch()找到自己的位置insert()

  2. 我知道你在構造函數中的一些額外的空間打造,但如果你插入足夠的項目,您的數組需要成長。插入需要比較大小和容量。

  3. 想想你的「轉移一切正確」的代碼。在紙上寫下(或使用索引卡)示例初始數組,執行gedanken插入,並在更新數組的同時遍歷代碼一個循環。你可能有一個錯誤。只是說...--)

  4. 你能用System.arraycopy()嗎?如果是這樣,請在插入或放大數組時使用它。

1

在for循環中,嘗試將j初始化爲size-1而不是size。另外,請注意,如果在插入時未檢查容量,程序將運行,但在插入完整陣列時將丟失最後一個元素。希望這可以幫助。