【发布时间】:2026-02-17 21:15:02
【问题描述】:
几天前我问了this 的问题,现在我有一个更具体的问题,因为我在我的程序上做了更多工作并添加了一些东西。基本上我从一个空的 ArrayList 开始,它应该保存通过控制台添加的生日。这部分我下来了+它打印了我添加的生日。但是如果我想添加另一个,它会打印我再次添加的第一个?我怎样才能让它打印出我到目前为止添加的所有生日?我将展示我目前拥有的代码
生日课
public class Birthday {
private String bdayKid;
private int age;
private boolean gift;
public Birthday(String bdayKid, int age, boolean gift) {
this.bdayKid = bdayKid;
this.age = age;
this.gift = gift;
}
//overridden toString() method
public String toString() {
return this.bdayKid + " turns " + this.age + "! They are" +
(this.gift ? "" : "not ") + " getting a gift.";
}
}
主类
public class MainClass{
public static void main(String []args) {
ArrayList<Birthday> bdays = getBirthdays();
printBirthdays(bdays);
}
//This method will return a list of birthdays
public ArrayList<Birthday> getBirthdays() {
ArrayList<Birthday> bdays = new ArrayList<Birthday>();
Scanner scan = new Scanner(System.in);
//create a birthday
Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
//add the birthday to arraylist of birthdays
bdays.add(bday);
return bdays;
}
//This method will print a list of birthdays
public void printBirthdays(ArrayList<Birthday> bdays) {
//iterate through each birthday and print out the result
for (Birthday bday : bdays) {
System.out.println(bday);
}
}
}
在一个冗长的 switch 语句中,我添加了这个选项:
System.out.println("Do you want to add another birthday?");
boolean anotherOne = scan.nextBoolean();
if (anotherOne == true) {
getBirthdays();
printBirthdays(bdays);
}
我是否需要在我的 for-each 循环中添加一个 if 语句?任何帮助表示赞赏!
【问题讨论】:
-
ehm ...您的代码已经在做您要求它做的事情,您还需要什么?如果您想要更多元素,只需在 while 循环中检查您的 anotherOne,然后将 anotherOne 的值重置为该循环的最后一条语句
-
"我怎样才能让它打印出我到目前为止添加的所有生日" getBirthdays() 中,您创建一个新的局部变量
ArrayList<Birthday> bdays,然后添加到该局部变量变量并返回它。因为每次调用该方法时,您都会创建一个新的本地 ArrayList,这些列表永远不会包含超过一个生日。 -
@OHGODSPIDERS 哦,不......我该如何解决这个问题?
-
不要总是创建新的本地对象。相反,为什么不将 List 设为类的字段并在构造函数中对其进行初始化。
-
@Stultuske 你的解释是有道理的,但是当我查看我的代码时我冻结了 T_T 你能大致解释一下代码中的样子吗?对不起,我是新手