2013-04-20 97 views
1

我是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,副本)

“已修正我的代码” 像凯文提到,数组是主要想法来存储这些值,但由于它的静态值它可以是完整的,但我可以使用expandcapacity方法来输入n-books,并且数组已满,它将数组扩展为x大小。谢谢!

+1

你知道列表的概念,数组,设定,收藏? – Juvanis 2013-04-20 22:25:35

+1

为了完成这项工作,您需要大量'Book'变量。因此,为了不手动声明大量未知变量,您可以使用'array'或像'List '这样的集合''ArrayList ''备份。 – 2013-04-20 22:25:54

回答

7

代码应该将每本书存储在列表中,以便稍后可以在代码中访问它们。除了标识代码中的对象之外,这个名称并不重要。即使您可以更改本地变量的名称book您的问题仍然存在。

您遇到的问题与范围和对象实例更相关。当您致电new Book(..)时,您将创建一本书的新实例。这本书范围的实例仅限于由while循环执行的代码块{}。这意味着在循环之外,书的实例是不可访问的。

为了访问外循环书的情况下,你可以在循环外创建了一本书,像这样:

Book book; 

while(...){ 
    book = new Book(...); 
} 

这种方法的问题是,你正在创建本书的几个实例,所以这本书的参考文献将被循环中每次迭代的最新书籍覆盖。

这就创造了持有多本书的必要性。立即可以想到一个数组,但是数组的大小是静态的,用户可以输入1..n的书。这不会使阵列成为存储书籍的好选择。

这是ListArrayList发挥作用的地方。 A List是一个保存多个对象实例的数据结构。它可以使用add(Object)方法轻松扩展。列表的完整描述和一个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()); 
    } 
+1

虽然您在这个答案中有一个观点,但请记住OP中的这些单词:*我是java *中的初学者。基于此,看起来像OP甚至不知道“ArrayList”如何在幕后工作,所以第一步将教授数组概念并提供数组解决方案。 – 2013-04-20 22:29:17

+0

@LuiggiMendoza我试图详细说明集合101 – 2013-04-20 22:42:51

+0

没有提供课程是的,现在它更好。 +1 – 2013-04-20 22:44:46