1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Arrays in Java

  1. Jun 26, 2007 #1
    I'm supposed to create a method that adds intergers to an array and keep it in sorted order. I'm supposed to search for the number in the array using binarySearch. I get an error that says arrayOutOfBound I don't know how to fix this. I have written the following code:
    elementData is the array,

    Code (Text):
     public void add(int value) {

          int index = binarySearch(elementData,value,0, size - 1);
         
          }
          for (int i = size; i > index; i--)
              {
               elementData[i] = elementData[i - 1];
               elementData[index] = value;
               size++;
              }
             
             }
    I appreciate any help :confused:
     
  2. jcsd
  3. Jun 26, 2007 #2
    I'm a little rusty in my Java,
    so your algorithm there seems to move every value up in order to make a spot to place the new value in the right sorted order right?

    The only thing I can see is what happens when the new value is lower than all other values? so it goes all the way to i=0, and elementData[i-1] will give try to get to elementData[-1] which would be out of the boundary of the array.

    So maybe adding and if(i=0) will fix that? so you just replace the 0'th element, since it was already moved up to [1].
     
  4. Jun 26, 2007 #3
    Thanks for your help
     
  5. Jun 26, 2007 #4

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Well, if the array's length is called size, then the elements of that array range from 0 to size - 1. However, your for loop starts with i=size, meaning you're past the end of the array.

    - Warren
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Arrays in Java
  1. Java class Arrays (Replies: 1)

Loading...