对于这个项目,我只能从书堆中删除最上面的一本书,而不能从另一本书的下面删除一本书。同样,我不能在另一本书下面添加一本书。我只能将另一本书放在书堆的顶部,才能将其添加到书堆中。在我的代码中,我从书堆中删除了Book E,但是现在我想添加另一本书。如何将新书(书号:F)添加到myBooks并打印列表?有一个指向我当前输出的屏幕截图的链接。
screenshot of current output
public class Driver
{
public static void main(String[] args)
{
Book[] myBooks = { new Book("A"), new Book("B"), new Book("C"), new Book("D"), new Book("E")};
PileOfBooksInterface<Book> bookPiles = new PileOfBooks<>();
System.out.println("Are there any books in the pile? " + bookPiles.isEmpty());
for (int index = 0; index < myBooks.length; index++)
{
Book nextItem = myBooks[index];
bookPiles.add(nextItem);
} // end for
System.out.println("\nTotal books in the pile:");
for (int index = 0; index < myBooks.length; index++)
{
System.out.println(myBooks[index]);
} // end for
System.out.println("\nRemoving the last book:");
bookPiles.remove();
Object[] arr = (bookPiles.toArray());
for (int index = 0; index < arr.length; index++)
{
System.out.println(arr[index]);
} // end for
System.out.println("\nAdding new book on top of the pile:");
// ???
}
}
最佳答案
这很简单。您可以使用ArrayList来存储所有书籍,而Java具有ArrayList的漂亮内置方法。您可以执行以下操作:
public class Driver
{
public static void main(String[] args)
{
Book[] myBooks = { new Book("A"), new Book("B"), new Book("C"), new Book("D"), new Book("E")};
ArrayList<Book> bookPiles = new ArrayList<Book>();
System.out.println("Are there any books in the pile? " + bookPiles.isEmpty());
for (int index = 0; index < myBooks.size(); index++)
{
Book nextItem = myBooks[index];
bookPiles.add(nextItem);//populating ArrayList
} // end for
System.out.println("\nTotal books in the pile:");
for (int index = 0; index < myBooks.size(); index++)
{
System.out.println(bookPiles.get(index));
} // end for
System.out.println("\nRemoving the last book:");
bookPiles.remove(bookPiles.size()-1); //removing the last element from the bookPile ArrayList
//Object[] arr = (bookPiles.toArray()); //No need for this line
for (int index = 0; index < bookPiles.size(); index++)
{
System.out.println(bookPiles.get(index));
} // end for
System.out.println("\nAdding new book on top of the pile:");
// you can write the code for adding at the top of the pile as follows:
bookPiles.add(0,new Book("E"));//0 is the first position in the ArrayList where we want to add data and all the elements will be shifted automatically.
//the above line will add the new book at the top of the pile.
for (int index = 0; index < bookPiles.size(); index++)
{
System.out.println(bookPiles.get(index)); //print all the books along with the new one
}
}
}
希望这对您有帮助。