Greetings all,
So I am working on a project where I select a number and it checks an array for that number, deletes it and moves everything down in the array. I have it working for the most part. It was part of an assignment and I got a 100 on the assignment, but I think that is because the teacher did not run into this particular issue I am having so I got lucky. Actually the assignment wasn't setup where he would ever run into this issue, but as I started playing with it more after the fact, I found that when I populated an array with all of the same numbers it only deleted half of them.

So for example if my array was 1,1,1,1,1,1,1,1,1,1

when I ran the delete, it tells me it only deleted 5 of the elements and when I do go see how many elements are in the array it does in fact show there are still 5 elements with a value of 1

my code for the delete class is below. I believe what is happening is that it finds the first instance at a[0] then moves a[1] down to fill a[0] but doesn't recheck if a[0] is again the number. you will notice in my class I have multiple counters and that was so I could show the teacher how many steps the process took. (This is a data structures class so doing much with N Steps and Big O notation)
I am having a problem figuring out how to get it to recheck a[0] to see if the number that got moved into it was the same (the number I want deleted).
Any assistance would be appreciated.

Wally

Code:

public void deleteElements()
{
int moveCount = 0;

System.out.print("Input the number you want to delete:\n");
int searchNumber = userInput.nextInt();

After line #23 where you update the total number of elements in the array, also decrement the counter variable so it checks the same element position again in the next loop pass; alternatively you could remove found elements from the right so you don't need this trickey.

kind regards,

Jos

01-26-2013, 07:45 PM

wfsteadman

Re: Not deleting items next to each other

Brilliant. I want to kick myself..... I was building while loops and doing a nested for loop. Lines and lines of code... I probably need a life, the assignment is already in and graded and I am sitting at home on a Saturday trying to improve it. But hey, learning is fun so thanks for the brilliant answer.

01-26-2013, 08:35 PM

JosAH

Re: Not deleting items next to each other

If I kicked myself for each and every silly mistake I made I'd be long dead or in a wheelchair ;-) I have been in this field for ages and I've seen most of those little pitfalls; here's a small tip (take it from an old sloppy sod like me): jot those things down somewhere or you'll make the same mistake again (I know I did in almost each and every language).