将本地对象数组复制到实例化对象数组,以供其他静态方法访问

Copying a local Array of objects to a instanced array of objects to be accessed by other static methods

我的问题是关于创建一个从静态方法中创建的局部变量的副本,并使它成为一个实例变量,可以被 class 中的其他静态方法使用。

这是我遇到问题的代码的特定部分。

static void createBooks() {
    Book [] inventory = new Book[maxBooks];
    System.out.println("How many books would you like to add?");
    int newBooks = keyboard.nextInt();
    int createBooks;
    if(newBooks>(maxBooks-findNumberOfCreatedBooks())) {
        System.out.println("Sorry, your bookstore has a capacity of " + maxBooks + ", and you have " + findNumberOfCreatedBooks() + " books already created.");
        System.out.println("Therefore we will add a maximum of " + (maxBooks-findNumberOfCreatedBooks()) + " to your collection.");
        createBooks = (maxBooks-findNumberOfCreatedBooks());

    }
    else
        createBooks=newBooks;

    for(int x =findNumberOfCreatedBooks(); x<createBooks;x++) { //creates a new book where one doesn't exist
        System.out.println("***Book"+x+"***");
        System.out.println("Please enter the name this book:");
        String name = keyboard.next();

        System.out.println("Please enter the author of this book:");
        String author = keyboard.next();

        System.out.println("Please enter the ISBN of this book:");
        keyboard.nextLine();
        long isbn = keyboard.nextLong();

        System.out.println("Please enter the price of this book:");
        double price = keyboard.nextDouble();

        inventory[x] = new Book(name,author,isbn,price);
    }

我正在尝试创建一个 Book 对象数组,然后可以通过其他静态方法访问该对象,例如名为 ChangeBooks() 的方法,该方法将允许用户修改他们使用 setName()、setTitle 创建的书籍()等

有没有办法创建一个从静态方法更改而来的书籍对象的实例数组,并且在方法外初始化时不指向空引用?

谢谢

您可以在定义此方法的 class 上将 inventory 设为静态字段:

class BookStuff {
    private static Book[] inventory;
    private static final int MAX_BOOKS = 5;

    static void createBooks() {
        inventory = new Book[MAX_BOOKS];
        // ...
    }

    static void readBook(int index) {
        inventory[index].read();
    }
}

注意实例属性不能被class方法(静态方法)修改。