2012-09-27 2 views
0

우리는 벡터에서 작업중인 내 comp 182 클래스의 프로젝트를 가지고 있지만 "정렬 된 벡터"를 만드는 데 집착하고 있습니다. 그것을 실행하려고하면 ArrayOutofBounds 오류가 발생합니다.

(이하 "howMany"변수가이 "addWord를 사용하여 어레이"theWords "
하고 코드가 10 개 개의 단어 입력 파일을 판독하여 다른 클래스에서 실행되고있는 현의 크기에 대한 카운트이며 "메서드를 사용하여 파일의 단어를"theWords "배열에 추가합니다.

여기에 내가 가지고있는 코드가 있습니다 :
[btw"compareTo "메서드 만 사용할 수 없습니다]Java - ordering/alphabetizing 문자열 배열

public void addWord(String newWord) { 
    //adds in words 
    if (howMany < theWords.length) { 
     theWords[howMany]= newWord; 
     howMany++; 
    } 
    else { 
     String t [] = new String[capacity+10]; 
     for (int i=0; i <capacity; i++){ 
      t[i] = theWords[i]; 
     } 
     theWords = t; 
     theWords[howMany] = newWord; 
     howMany++; 
    } 

    //ordering words 
    for(int g = howMany - 1, z = howMany ; g < howMany; g--, z--) { 
     if(newWord.compareTo(theWords[g]) < 0) { 
      theWords[g] = theWords[z]; 
      theWords[g] = newWord; 
     } 
      else 
      newWord = theWords[z];   
    } 
     howMany++; 
    } 

도움을 주시면 감사하겠습니다.

+1

어떤 라인은 예외를 가져오고 staccktrace을 게시하시기 바랍니다 있습니다 – PermGenError

답변

2

배열 Z = 길이로 배열의 용량

theWords[g] = theWords[z] 

루프의 처음 실행에 실패 계산서에 따라 (길이 배열의 마지막 인덱스 - 1). 보조 노트에, 루프, 당신은 g <이 howMany 항상 true가됩니다 ... 그래서 당신이 무한 루프를해야합니다, 처음

g = howMany - 1 

를 설정하고이를 감소. 이 무한 루프는 g 또는 z가 0 미만이 될 때 인덱스가 경계를 벗어날 수 있습니다.

1

이 함수가 실행되기 전에 howMany == capacity - 1 인 경우 문제가 발생합니다. 어떻게됩니까

: 당신은 howMany = capacity가 된 다음 howMany 증가 (// 즉 추가) 경우의 첫 번째 지점에 가서 당신은 z = howMany를 할당하고 그 경계의 외측에 배열 액세스 : theWords[g] = theWords[z];.

또 다른 점은 변수를 증가시키지 않아야한다는 것입니다.이 변수는 capacity+=10이어야합니다. 여기

내 변형입니다 :

import java.util.Arrays; 
import java.util.Random; 
public class OrderedArray{ 

    int howMany = 0; 
    String[] theWords = new String[10]; 

    public void addWord(String newWord) { 

    //don't accept nulls 
    if(newWord == null) { 
     return; 
    } 
    //if length is reached increase the array 
    if(howMany >= theWords.length - 1) { 
     theWords = Arrays.copyOf(theWords, theWords.length+10); 
    } 

    //go through existing words and add newWord if it is less then met value 
    boolean isAdded = false; 
    for(int idx = 0; idx < howMany && theWords[idx] != null; idx++){               
     if(newWord.compareTo(theWords[idx]) < 0){ 
     isAdded = true; 
     String valToShift = theWords[idx]; 
     theWords[idx] = newWord; 

     //copy all values after the met index 
     for(int shIdx = idx+1; shIdx <= howMany && shIdx < theWords.length; shIdx++){ 
      String tmp = theWords[shIdx]; 
      theWords[shIdx] = valToShift; 
      valToShift = tmp; 
     }   
     break; 
     } 
    } 

    //if a value was not added then add it 
    if(!isAdded){ 
     theWords[howMany] = newWord; 
    } 
    ++howMany; 
    } 

    public String toString(){ 
    StringBuffer sb = new StringBuffer("howMany:"); 
    sb.append(howMany); 
    for(int idx = 0; idx < howMany; idx++){ 
     sb.append(","); 
     sb.append(theWords[idx]); 
    } 
    return sb.toString(); 
    } 


    public static void main(String[] args){ 
    OrderedArray m = new OrderedArray(); 
    Random r = new Random(System.currentTimeMillis()); 
    for(int i = 0; i < 210; i++){ 
     m.addWord(Math.abs(r.nextInt())+ ""); 
    } 
    System.out.println(m); 

    OrderedArray m1 = new OrderedArray(); 

    m1.addWord("c"); 
    m1.addWord("d"); 
    m1.addWord("a"); 
    m1.addWord("cd"); 

    System.out.println(m1); 

    } 

}