gpt4 book ai didi

java - 将 Main 中发生的另一个类文件中启动的数组对象添加到堆栈中

转载 作者:行者123 更新时间:2023-12-02 09:16:00 25 4
gpt4 key购买 nike

我正在尝试将 Main 中的启动对象(启动发生在 main 中,但从圣诞节类文件中的一个类中提取:courtney.addGift("Dog"); .. 等)放入 myHoliday Stack .

如何将主 Courtney.addGift("Dog") 中的启动对象(addGift 从 Christmas 类文件中拉出)放入 myHoliday 堆栈中?

这是圣诞节文件:

圣诞节

    public class Christmas {

ArrayList<String> gifts;
// add a constructor that takes no arguments and initializes
// the previous properties

public Christmas()
{

gifts = new ArrayList<String>();
}

// add a method called addGift that accepts a string
// and adds it to the gifts data structure
public void addGift(String gift)
{
gifts.add(gift);
}

}

主要

 public static void DemoChristmas()
{
// create a couple of Christmas objects and add them to a stack
//Pop them off the stack and print them as you go

Christmas courtney = new Christmas();
Christmas alexandra = new Christmas();
Christmas bobby = new Christmas();
Christmas jackie = new Christmas();

Stack<Christmas> myHoliday = new Stack<Christmas>();

// initiate the Christmas objects
courtney.addGift("Dog");
alexandra.addGift("Hat");
jackie.addGift("Car");
bobby.addGift("Socks");
// add them to the stack

}

最佳答案

  1. 在您的圣诞节类(class)中制作合适的 gettersetter
  2. 如果您想打印 stack 的内容,您需要重写 Christmas 类的 toString()
class Christmas {
private ArrayList<String> gifts;

public Christmas() {
gifts = new ArrayList<String>();
}

public void addGift(String gift) {
gifts.add(gift);
}

public ArrayList<String> getGifts() {
return gifts;
}

public void setGifts(ArrayList<String> gifts) {
this.gifts = gifts;
}

@Override
public String toString() {
StringBuilder giftName = new StringBuilder();
for (String gift : gifts){
giftName.append(gift);
giftName.append(" ");
}
return giftName.toString().trim();
}
}

此外,这不是打印堆栈的正确方法。

private static void printStack(Stack<Christmas> stack) {
while (!stack.isEmpty()) System.out.println(stack.pop());
}

可能是一种方式。

关于java - 将 Main 中发生的另一个类文件中启动的数组对象添加到堆栈中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982870/

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