[英]Changing object name with input
我是Java的初学者,我想知道是否可以通过输入更改主类中对象的名称? 例如我得到以下代码:
while(!answer.equals("stop"))
{
//Enters book's information and stores it in the object book1
System.out.println("Book-" + count);
title = input.next();
author = input.next();
ISBN = input.next();
copies = input.nextInt();
Book book1 = new Book(title,author, ISBN, copies);
printLn("");
printLn("Do you wish stop adding books? N || stop");
answer = input.next();
}
我想继续添加新书,直到在出现提示时写停止字为止,但是当然不更改名称,它将继续将数据添加到同一对象。 是否可能,还是需要继续使用以下方法制作新书对象:书等=新书(书名,作者,ISBN,副本)
“纠正我的代码”像凯文提到的那样,数组是存储这些值的主要思想,但由于其静态值而可能已满,但是当输入n本书并且数组已满时,我可以使用expandcapacity方法它将数组扩展为x大小。 谢谢!
该代码应将每本书存储在一个列表中,以便以后可以在代码中对其进行访问。 除了在代码中标识您的对象外,该名称实际上并不重要。 即使您可以更改本地变量book
的名称,您的问题仍然会保留。
您遇到的问题与范围和对象实例有关。 调用new Book(..)
将创建一本书的新实例。 这本书的作用域实例仅限于while循环执行的代码块{}
。 这意味着在循环之外无法访问书籍实例。
为了在循环外访问book的实例,您可以像这样在循环外创建一本书:
Book book;
while(...){
book = new Book(...);
}
这种方法的问题在于,您要创建书籍的多个实例,因此对于该循环的每次迭代,书籍的引用将被最新的书籍覆盖。
这创造了某种东西可以容纳多本书的必要性。 立即可以想到一个数组,但是数组的大小是静态的,用户可以输入1..n本书。 这并不是使数组成为存储书籍的好选择。
这就是List
和ArrayList
起作用的地方。 List
是包含多个对象实例的数据结构。 使用add(Object)
方法可以轻松地对其进行扩展。 List和ArrayList的完整描述超出了此答案的范围,但是我提供了以下资源: http : //docs.oracle.com/javase/tutorial/collections/
最终解决方案
List<Book> books = new ArrayList<Book>();
while(!answer.equals("stop"))
{
//Enters book's information and stores it in the object book1
System.out.println("Book-" + count);
title = input.next();
author = input.next();
ISBN = input.next();
copies = input.nextInt();
Book book1 = new Book(title,author, ISBN, copies);
books.add(book1);
printLn("");
printLn("Do you wish stop adding books? N || stop");
answer = input.next();
}
//Iterating the book list outside the loop
for(Book book:books){
//this call may vary depending on the book implementation
System.out.println(book.getTitle());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.