1

I'm making a store in java and I'm trying to add a new item to an array, but I can't figure out how to make it work. add.items(i); won't work because that's only for ArrayList, and a requirement for this task is that I have to use an array. The purpose of this function is it checks if there is an empty space in the array, which has a maximum size of 10, and it adds an item if it's not full.

public boolean addItem (Item i){
    for (int i = 0; i < items.length; i++) {
        if (items[i] == null) {
            add.items(i);
            return true;
        }
        return false;
    }
}
1
  • 2
    add.items(i); won't work for an ArrayList either. Commented Feb 14, 2019 at 17:53

1 Answer 1

1

Your code won't work because you are using duplicate variables i.

Try this instead:

public boolean addItem (Item item) {
    // Rename loop variable
    for (int x = 0; x < items.length; x++) {
        if (items[x] == null) {
            // Asign the incoming item to items array in case this position is empty
            items[x] = item;
            return true;
        }
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

You probably want to move that return false one level later... otherwise it will never get beyond the first iteration of the loop
May I suggest renaming i to item for improved readability. One letter variable names are only ok in for loops and similar.

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.