0

I have a project in my comp 182 class we're working on vectors but I'm stuck on making an "ordered vector". When I try to run it I get an ArrayOutofBounds error.

(The "howMany" variable is the count for the size of the Strings in the array "theWords"
And the code is run from another class that reads an input file with 10 words in it,using this "addWord" method to add the words from the file into the "theWords" array.)

Here's the code I have so far:
[btw we're not allowed to use the "Array" methods only "compareTo"]

 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++;
  }

Any help is much appreciated!

1
  • 1
    what line are you getting the Exception and please post the staccktrace Commented Sep 27, 2012 at 23:04

2 Answers 2

2

Depending on the capacity of the array, the statement

theWords[g] = theWords[z]

will fail on the first execution of the loop, as z = length of the array (last index in the array is length - 1). On a side note, in the loop, you initially set

g = howMany - 1

and then decrement it, so g < howMany will always be true...you will have an infinite loop. This infinite loop could also cause the index out of bounds exception when g or z go below 0.

Sign up to request clarification or add additional context in comments.

Comments

1

You have a problem if howMany == capacity - 1 before the function is executed.

What happens: you go into the first branch of if (//adds in words) then you increment howMany which became howMany = capacity and then you assign z = howMany and access an array outside its bounds: theWords[g] = theWords[z];.

Another thing is that you do not increment capacity variable, which has to be capacity+=10.

Here is my variant:

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);

  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.