0

So the issue is I've created an object array that takes user input and stores the object. I want to remove objects using a method that finds them via their id number and removes them from the array. Honestly, I can't figure out why I can't get away from the errors. (I know my code is wrong, I just don't understand what is wrong per se. The book object is in a separate file, but I can post that as well if needed. Thank you.



import java.util.Scanner;

public class Inventory {
    private int size;
    private Book[] inventory;
    private Scanner scan = new Scanner(System.in);
    
    public void addBook() { //open method addBook
        System.out.print("Enter the book id number: ");
        int id = scan.nextInt();
        for (int i = 0; i < inventory.length; i++) {
            for (int j = i+1; j <inventory.length; j++)
                if (inventory[i].equals(inventory[j])) {
            System.out.print("This book is already in the inventory" );
                }
        }
        System.out.print("Enter book title: ");
        String title = scan.nextLine();
        System.out.print("Enter book price: ");
        double price = scan.nextDouble();
        Book book = new Book(id, title, price);
        inventory[size++] = book;
        
    } //Close method addBook
    
    public void removeBook() { //open method removeBook
        System.out.print("Enter the book id of the book you want to remove: ");
        int id = scan.nextInt();
        for(int i = 0; i < inventory.length; i++) {
            if(inventory[i] != null && id == inventory[i].getId) {
                (inventory[size] - inventory[i]);
            }
        }
    } //Close method removeBook
 
1
  • 1
    Arrays in Java are static data structures (not the static keyword, static as in "not dynamic"). You can't add or remove indices from an array. You can set an index to null in order to lose the reference, but the index doesn't go away. It sounds like what you want is an ArrayList, which behaves similarly to an array, except the number of indices is dynamic. Commented Mar 29, 2021 at 23:06

1 Answer 1

1

In this case it is better to use the ArrayList instead of just an array. So instead of

private Book[] inventory;

You would do

private ArrayList<Book> inventory;

I suggest you research ArrayLists for Java. One of the methods for an ArrayList is the remove method i.e.

inventory.remove(int index);

Use caution when doing the remove method as all indices after the index that is to be removed will shift to the left.

Sign up to request clarification or add additional context in comments.

Comments

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.