nasrot
nasrot

Reputation: 33

How to loop through ArrayList of objects and make it print everything?

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!

Upvotes: 1

Views: 859

Answers (3)

LitVitNik
LitVitNik

Reputation: 29

IMO the best way to do this is splitting your getBirthdays() to printBirthdays() and addBirthday(). Here is the code and you can use your own logic to loop the input:

import java.util.ArrayList;
import java.util.Scanner;

public class MainClass {
    static ArrayList<Birthday> bdays = new ArrayList<>();
    public static void main(String []args) {

        while(true) {
            //Use this method every time you need to add new BDay
            addBirthday();
            //Use this method to print all BDays in ArrayList
            printBirthdays();
        }
    }
    public static void addBirthday(){
        Scanner scan = new Scanner(System.in);
        Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
        bdays.add(bday);
    }
    public static void printBirthdays(){
        for(Birthday b: bdays){
            System.out.println(b);
        }
    }
}

Upvotes: 1

You have a serious problem in understanding Java. First, you need to understand a concept, the scope of a variable.

If you create a variable inside a function, then the scope of the variable is in the function only.

You have different instances of ArrayList<Birthday> with the identifier bdays. One instance that you defined in void main function, and other instances are created each time you call getBirthdays() method. In the switch statement, when you call getBirthdays(), a new ArrayList<Birthday> is formed and returned by the function, while your original ArrayList<Birthday> bdays remains unchanged. And when you call printBirthdays(bdays) it takes argument as the array created by you in the first line of your main method instead of a new ArrayList returned by getBirthdays() method. Hence, it does not print the new Brithday. So, you can change your code something like follows:

Main class

public class MainClass{
   public static void main(String []args) {
      // Instantiate your one and only bdays array
      ArrayList<Birthday> bdays = new ArrayList<Birthday>();
      getBirthdays(bdays);
      printBirthdays(bdays);
   }

   //This method will return a list of birthdays
   public void getBirthdays(ArrayList<Birthday> bdays) { 
      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);

      // Good practice to close a scanner
      scan.close();
   }

   //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,

System.out.println("Do you want to add another birthday?");
                boolean anotherOne = scan.nextBoolean();
                if (anotherOne == true) {
                    getBirthdays(bdays);
                    printBirthdays(bdays);
                }

Note that, Java passes objects as reference, so if you pass you **bdays** to getBirthdays(bdays) then every change inside this function done to bdays will also occur to your original bdays in main method. More precisely, they are the same ArrayList in your memory, and the variables bdays in two different methods main and getBirthdays(bdays) are just different identifiers referencing to same ArrayList<Birthday> that you created at the start of the function and passed as a reference to the getBirthdays method. Check other relevant tutorials on passing variables by reference in java.

Upvotes: 1

Renis1235
Renis1235

Reputation: 4700

Add field in the Birthday class:

private boolean printed = false;

Then on your print function:

 //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) {
         if(!bday.isPrinted())
         {
            System.out.println(bday);
            bday.setPrinted(true);
         }
      }
   }

Upvotes: 0

Related Questions