【发布时间】: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