A few days ago I asked this question, and now I have a more specific one, since I worked on my program some more and added a few things. Basically I start out with an empty ArrayList which is supposed to hold birthdays that are added via console. This part I got down + it prints the birthday I add. But if I want to add another one, it prints the first one I added again? How could I make it print out all the birthdays I have added this far? I'll show the code I have so far
Birthday class
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.";
}
}
Main class
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);
}
}
}
and inside a long-ish switch statement i added this option:
System.out.println("Do you want to add another birthday?");
boolean anotherOne = scan.nextBoolean();
if (anotherOne == true) {
getBirthdays();
printBirthdays(bdays);
}
Do I need to add an if statement inside my for-each loop? Any help is appreciated!
getBirthdays()you create a new local variableArrayList<Birthday> bdaysand then add to that local variable and return it. Since every time you call that method you create a new local ArrayList those Lists will never contain more than one Birthday.