0

I'm really hoping I can convey my intentions here:

I have a class called ("Branch") (I believe it is called an Object) and I have 2 instances of branches.

Basically (in my main class):

    private static Branch branch1 = new Branch();
    private static Branch branch2 = new Branch();

I know how to (on a basic level) add to a branch and how to remove from branch1.

(in my Branch class file):

    public void addPet(VirtualPet pet) {
        pets.add(pet);
    }

    public void removePet(String name) {
        for (int i = 0; i < pets.size(); i++) {
            if (pets.get(i).getName().equals(name)) {
                pets.remove(i);
            }
        }
    }

These work fine. But I'm trying to do a transfer from 1 branch to another branch (ex: branch1 to branch2).

I figure my removePet method would be the same, but I'm wondering how do I add that pet to the other branch? I know how to add a completely new pet, but I'm not sure how to pull the data from the pet I'm deleting and use that to add the new pet.

1 Answer 1

2

The answer is simple, return remove the item and add to the other branch

// return the pet
public VirtualPet removePet(String name) {
        for (int i = 0; i < pets.size(); i++) {
            if (pets.get(i).getName().equals(name)) {                
                return pets.remove(i); // API  https://docs.oracle.com/javase/8/docs/api/java/util/List.html#remove-int-
            }
        }
        return null;
    }

// then you can add this to other object
VirtualPet pet = branch1. removePet("something");
if (pet != null) {
    branch2.addPet(pet);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick response!! It's taking me a minute to get everything setup, but I think i understand. you're just returning an entire object instead of like a string or int (it's my first time returning an object). And it looks like the top part is both removing the pet and returning the pet to use to add in the 2nd part.
The "removePet" method is giving me an error saying "missing return statement" because the return statement is in the if statement.
@jrob11, you need to add return null at the end of the method. Because if the name doesn't exist you still need to return something
I feel smart right now (i have limited knowledge on Java, still learning!) But before I got your response , that's exactly what I did "return null" and everything worked 100%!! Thank you very much! Upvoted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.