Start New Discussion within our Software Development Community

My Question was

Write a program to collect and store all the cards to assist the users in finding all the cards in a
given symbol.

This cards game consist of N number of cards. Get N number of cards details from the user and store
the values in Card object with the attributes symbol and number.

Store all the cards in a map with symbol as its key and list of cards as its value. Map is used here to
easily group all the cards based on their symbol.

Once all the details are captured print all the distinct symbols in alphabetical order from the Map.
For each symbol print all the card details, number of cards and their sum respectively.

My Solution to the problem was .

    import java.util.*;

    public class CollectCards {

        protected ArrayList<Integer> array;
        protected Map<String,ArrayList<Integer>> card;

        public CollectCards(){
            this.array = new ArrayList<Integer>();
            this.card = new HashMap<String,ArrayList<Integer>>();
        }

        public void addCard(String name,int number) {
            if(this.card.containsKey(name)) {
                 this.card.get(name).add(number);             
            }else {
                this.array.add(number);
                this.card.put(name,this.array);
           }

        }

        public void display(){
           for(Map.Entry<String,ArrayList<Integer>> card : this.card.entrySet()){
              System.out.println(card.getKey()+"\t"+card.getValue());
           }
        }

        public static void main(String[] args){
           Scanner input = new Scanner(System.in);
           CollectCards card = new CollectCards();

           do{
            System.out.println("Enter the card details");
            card.addCard(input.next(),input.nextInt());            
            System.out.println("Want to repeat again!!!");
        }while(input.next().equals("Yes"));

        card.display();
      }
     }

Excepted Input:
1) s 1
2) s 2
3) s 3
4) s 4
5) n 1
6) n 2
7) m 1

Excepted output:
s -> [1,2,3,4]
n -> [1,2]
m -> [1]

Output I got from the above program
s -> [1,2,3,4]
n -> [1,2,3,4]
m -> [1,2,3,4]

Start by reading the instructions...
"store the values in Card object with the attributes symbol and number."

... but also, when you need to add a new key/value pair you use the unhelpfully-named array for the value. You keep adding numbers to that, so (1) it keeps getting bigger and (2) all the keys point to exactly that same ArrayList.

... and while I'm on the subject of variables names, you have three variables called card in just a 41 line source file, and none of them represents a Card. One is a CollectCard object (what happened to class names being nouns?), one is a Map, and one is a Map.Entry. Now, what are the chances of getting confused - I know I was.

This question has already been answered. Start a new discussion instead.