-1

This is regarding a Java homework assignment: I want to create a method that takes the list of cards as a parameter and prints all the cards to the screen. Each card should print all stored information so that I can use the newly created method to print all the cards. And it is required for me to use the Array list of Card objects as a parameter.

I have three class in this program, namely - Main.java, HandDrawn.Java, and Card.java. Basically the program tracks the Christmas card information with the sender's name and if they are hand written or not. I'm stuck at this point as I don't know how to use ArrayLists properly and pass them through a method in order to print them.

public class Main {


    public ArrayList<Card> cardsList = new ArrayList<>();


    public static void main (String [] args){

        Main myApp = new Main();

    }
    public void printAll (ArrayList<Card> cardArrayList){
        System.out.println(cardArrayList);

        HandDrawn sender1 = new HandDrawn("Anna", true);
        HandDrawn sender2 = new HandDrawn("Kalle", false);
        cardsList.add(0, sender1);
        cardsList.add(1, sender2);
    }


    public void printing(ArrayList<Card> cardsList) {
        System.out.println(cardsList);
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
iamsumitd
  • 1
  • 4

2 Answers2

0

Your logic does print the List before ot has anything in it. Try adding something to the List before printing the content.

public void printAll (ArrayList<Card> cardArrayList){
    System.out.println("List content: " + cardArrayList.toString()); // <- Empty List at this point

    HandDrawn sender1 = new HandDrawn("Anna", true);
    HandDrawn sender2 = new HandDrawn("Kalle", false);
    cardsList.add(0, sender1);
    cardsList.add(1, sender2);
}

The output is then:

List content: []

boutta
  • 24,189
  • 7
  • 34
  • 49
  • Okay, let's say I do this - `public void printAll (ArrayList cardArrayList){ HandDrawn sender1 = new HandDrawn("Anna", true); HandDrawn sender2 = new HandDrawn("Kalle", false); cardsList.add(0, sender1); cardsList.add(1, sender2); System.out.println(cardArrayList); // <- Empty List at this point }` how do I simply call this method by passing the relevant arraylist as a parameter so that I can use this method anywhere? – iamsumitd Oct 31 '19 at 14:41
  • The filling of the List, e.g. the part with add should go to the main-method. The rest can be done as Dima explains in his answer https://stackoverflow.com/a/58645683/15108 – boutta Oct 31 '19 at 16:46
0

Please see this examples: how to print ArrayList in java

System.out.println("Print Arraylist using for each loop");
for( String strDay : aListDays ){
    System.out.println(strDay);
 }
Panteleev Dima
  • 175
  • 2
  • 18