I try to remove an element from java array and shift the array, update the total value and the count. Here is the code segment that I wrote, it gives me wrong result, how can I fix it?
public void remove(int index)
{
if(index > count-1 || index <0)
System.out.println("Incorrect index.");
else{
if(index ==1){
total -= numbers[index];
numbers = new int [0];
count--;
}else{
total -= numbers[index];
for(int i=index; i < count; i++)
numbers[i] = numbers[i+1];
count--;
}
}
}
I test the code with this;
NumberList n10 = new NumberList(-5);
n10.add(45);
n10.remove(0);
System.out.println(n10);
n10.add(12);
n10.add(25);
n10.add(20);
System.out.println(n10);
n10.remove(1);
n10.remove(1);
n10.remove(0);
System.out.println(n10);
I get
Size of the array must be greater than 0. [Empty List] [12, 25, 20]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NumberList.remove(NumberList.java:113)
at Prelab8.main(Prelab8.java:102)