gpt4 book ai didi

java - 如何向数组添加新条目?

转载 作者:行者123 更新时间:2023-12-02 09:46:59 26 4
gpt4 key购买 nike

对于这个项目,我只能从书堆中删除最上面的一本书,而无法从另一本书下面删除一本书。同样,我不能将一本书添加到另一本书下面。我只需将另一本书放在书堆的顶部即可将其添加到书堆中。在我的代码中,我从书堆中删除了 Book E,但现在我想添加另一本书。如何添加新书(书:F)到myBooks并打印列表?有一个指向我当前输出的屏幕截图的链接。

screenshot of current output

enter image description here

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:");
// ???

}
}

最佳答案

有了书堆,你不再需要一堆书本类(class),并且会按照你期望的方式工作。

public class Driver {
public static void main(String[] args) {
Stack<Book> bookPiles = Arrays.asList(new Book("A"), new Book("B"), new Book("C"), new Book("D"), new Book("E")).stream()
.collect(Collectors.toCollection(Stack::new));
System.out.println("Are there any books in the pile? " + !bookPiles.isEmpty());
System.out.println("\nTotal books in the pile:");
bookPiles.stream().forEach(System.out::println);
System.out.println("\nRemoving the last book:");
bookPiles.pop();
bookPiles.stream().forEach(System.out::println);
System.out.println("\nAdding new book on top of the pile:");
bookPiles.push(new Book("F"));
bookPiles.stream().forEach(System.out::println);
}
}

如果 PileOfBooks 已经编写并且已知可以按照您所描述的方式工作,那么您只需将一本书添加到 PileOfBooks 中,就像开始添加书籍时所做的那样。

bookPiles.add(new Book("F"));

关于java - 如何向数组添加新条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com