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]