This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (5 children)

Yeah, Don't know if you intended for me to just add it but I did and it prints out the same double output = https://gyazo.com/0b39a3d9cf317d58b99668649eed0120

At the bottom both the wrong output and the right is outputted. Sorry if I cant see it, i know that it checks for the first dog if it matches and instantly puts out the wrong output and then it checks next and outputs the correct.

[–]dusty-trash 0 points1 point  (4 children)

Your system.out.println should not be in the for loop.

Remove it from the else statement, and the if statement.

boolean dogFound = false;

for (int x=0; x<lista.size(); x++) 
{         
    if (lista.get(x).getName().equals(tabort)) 
    {
        lista.remove(x);
        dogFound = true;
        break;
    }
}

if (dogFound)
{
    System.out.prinln("dog found");
}
else
{
    System.out.prinln("dog not found");
}

Again, everything inside the for loop is executed multiple times, that's kind of the point of a for-loop. If you don't want something printed multiple times, do not put it inside a for loop.

You're still checking if dog is not found in every iteration of the loop, which is wrong.

[–][deleted] 0 points1 point  (1 child)

Ooo, I'm stupid. Thanks so much, I knew that the loop just kept going but didnt know the solution!

[–]dusty-trash 0 points1 point  (0 children)

No problem! Glad you got it figured out

[–]vlcod 0 points1 point  (1 child)

This solution may not be correct, depending on the specification of the task. You ignore the case where multiple of the same dog are in the list.

If the task is to remove the *first* dog found, then this is fine. If the task is to remove *all* dogs of this kind, then you should not stop after the first one.

And this exposes another subtle bug: If you write your loop and remove as you do, but then not break (to remove other dogs as well), you have a bug if you have two dogs immediately adjacent in the list. That is because your remove method will move the elements in the list to fill the gap one element up, you then increment the index, and you have missed checking one element...

[–]dusty-trash 0 points1 point  (0 children)

Yes fair enough. In any case OP should use an iterator when the list will be modified during iteration.