public void removeDups() {
int i, k, j, lastFound = 0;
if (this.nElements < 1) {
System.out.println("Empty Array");
} else {
for (i = 0; i < this.nElements; i = lastFound) //outer loop
{
for (j = i + 1; j < this.nElements; j++) {
if (this.arr[i] == this.arr[j]) {
lastFound = i;
for (k = i; k < this.nElements; k++) {
this.arr[k] = this.arr[k + 1];
}
this.nElements--;
break;
}
}
}
for (i = 0; i < this.nElements; i++) {
System.out.println(this.arr[i]);
}
}
}
the previous method removes duplicates from the object invoking it (Array),the problem is that i want the outer loop to begin from a certain position every increment, i assign the value of that position to the variable lastFound and put that variable in the incremental part of the loop but the program goes to infinite loop and never stops, what is the problem with that?
You’re setting
i = lastFoundat every iteration. At the start of the outer loop, initializelastFoundtoi + 1. That way it will increment normally if you don’t resetlastFound.Alternatively, get rid of
lastFoundand when you find a match, seti = i - 1, start thekloop ati + 1instead ofi, and change the increment expression in the outer loop fromi = lastFoundtoi++. I would also simplify your code by usingSystem.arraycopy: