从java数组中删除对象时出现问题

从java数组中删除对象时出现问题,java,Java,问题是我创建了一个对象数组,它接受用户输入并存储对象。我想使用一种通过id号查找对象并将其从数组中删除的方法来删除对象。老实说,我不明白为什么我不能摆脱这些错误。(我知道我的代码是错的,我只是不明白是什么错了。book对象在一个单独的文件中,但如果需要,我也可以发布。谢谢 import java.util.Scanner; public class Inventory { private int size; private Book[] inventory; pri

问题是我创建了一个对象数组,它接受用户输入并存储对象。我想使用一种通过id号查找对象并将其从数组中删除的方法来删除对象。老实说,我不明白为什么我不能摆脱这些错误。(我知道我的代码是错的,我只是不明白是什么错了。book对象在一个单独的文件中,但如果需要,我也可以发布。谢谢



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
 

导入java.util.Scanner;
公共类目录{
私有整数大小;
私人书籍[]存货;
专用扫描仪扫描=新扫描仪(System.in);
public void addBook(){//open方法addBook
System.out.print(“输入图书id号:”);
int id=scan.nextInt();
对于(int i=0;i对于(int j=i+1;j,在这种情况下,最好使用ArrayList而不仅仅是数组

private Book[] inventory;
你会的

private ArrayList<Book> inventory;

执行remove方法时要小心,因为要删除的索引之后的所有索引都将向左移动。

Java中的数组是静态数据结构(不是static关键字,静态如“not dynamic”)。您不能添加或删除数组中的索引。您可以将索引设置为
null
,以丢失引用,但索引不会消失。听起来您想要的是一个,它的行为类似于数组,只是索引的数量是动态的。
inventory.remove(int index);