【问题标题】:Copying a local Array of objects to a instanced array of objects to be accessed by other static methods将本地对象数组复制到实例化对象数组中,以供其他静态方法访问
【发布时间】:2018-06-29 18:16:10
【问题描述】:

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

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

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() 创建的书籍等等

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

谢谢

【问题讨论】:

    标签: java arrays object pass-by-reference


    【解决方案1】:

    您可以在定义此方法的类上将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();
        }
    }
    

    请注意,instance 属性不能被 class 方法(静态方法)修改。

    【讨论】:

    • 感谢您的帮助!我最终做的是在 main 方法中创建 Book [] 库存,然后每个需要使用它的静态方法将其作为参数,例如: public static void createBooks(Book [] inventory) {...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2016-07-17
    • 2011-06-26
    相关资源
    最近更新 更多