2015-01-21 3 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

답변

0

이 숙제가 있습니까? 나는 그것이라고 생각한다. 그래서 나는 단지 완전한 아이디어가 아닌 몇 가지 아이디어 만 줄 것이다. 배열이 정렬되어 있기 때문에

  1. , 당신은 당신이 생성자에서 몇 가지 여분의 공간에 구축 알아,하지만 당신은 충분히 항목을 삽입 할 경우, 배열 것 insert()

  2. 에 대한 위치를 찾을 수 Arrays.binarySearch()을 사용할 수 있습니다 성장할 필요가있다. 삽입물은 크기와 용량을 비교해야합니다.

  3. "모든 것이 바뀌십시오"코드에 대해 생각하십시오. 예를 들어 초기 배열을 종이에 적어 (또는 인덱스 카드를 사용하여) 작성하고, gedanken 삽입을 수행하고, 배열을 업데이트 할 때 한 번에 하나의 코드 루프를 반복하십시오. 거기에 버그가있을 가능성이 있습니다. 그냥 말하면 ... :-)

  4. System.arraycopy()을 사용할 수 있습니까? 그렇다면 배열을 삽입하거나 확대 할 때 사용하십시오.

1

for 루프에서는 크기 대신 size-1로 j를 초기화 해보십시오. 또한 삽입시 용량을 확인하지 않으면 프로그램이 실행되지만 전체 배열에 삽입 할 때 마지막 요소는 손실됩니다. 희망이 도움이됩니다.