CB89
CB89

Reputation: 3

Issue with removing an object from an array java

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
 

Upvotes: 0

Views: 68

Answers (1)

LuckyBandit74
LuckyBandit74

Reputation: 417

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.

Upvotes: 1

Related Questions