Reputation: 340
I am writing a program that creates an array with 100 random (long) elements:
main
byte maxSize = 100;
HighArray arr = new HighArray(maxSize);
for (byte j =0; j < maxSize; j++)
arr.insert((long)(Math.random()*99));
When I call the removeMax() method which is in the HighArray class
public long getMax()
{
long max = -1;
for (byte i =0; i < nElems; i++)
{
if(max < a[i])
max = a[i];
}
return max;
}
public long removeMax()
{
long max = getMax();
delete(max);
return max;
}
public boolean delete(long value)
{
int j;
for(j=0; j<nElems; j++) // look for it
if( value == a[j] )
break;
if(j==nElems) // can't find it
return false;
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
I get the array out of bounds : 100 exception. I assume this means that my array is out of bounds by 100 elements, which doesn't make sense to me since I'm deleting elements from it, not adding any. I did not get any errors when I initially created the array.
According to my IDE (Intellij IDEA), the problem happens when I call removeMax() from main.
If I am misunderstanding the error please let me know and clarify it for me. If more details or code is needed, let me know.
Upvotes: 2
Views: 315
Reputation: 23503
From what I can tell with the code you have, the problem is here:
a[k] = a[k+1];
Do this instead:
a[k] = a[k-1];
You assign K the value of J
, and when J
is on the last iteration (100), you add 1 to it, and thus get a value of 101, which is more than the allotted 100.
Upvotes: 1