Java 3RD Year 2.1
Java 3RD Year 2.1
Aim:
Playing cards during travel is a fun filled experience. For this game they wanted to collect all
four unique symbols. Can you help these guys to collect unique symbols from a set of cards?
Create Card class with attributes symbol and number. From our main method collect each card
details (symbol and number) from the user. Collect all these cards in a set, since set is used to
store unique values or objects. Once we collect all four different symbols display the first
occurrence of card details in alphabetical order.
Apparatus Required:
IntelliJ Idea
JVM
Code:
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
List<Integer> cardValue = new ArrayList<Integer>();
HashMap<String, List<Integer>> mp = new HashMap<>();
HashMap<String, Integer> firstEntry = new HashMap<>();
if(mp.containsKey(cardType)){
if(cardValue.contains(value)){
System.out.println("No same card type have same value.\nProcess
terminated.");
System.exit(0);
}
cardValue = mp.get(cardType);
cardValue.add(value);
}
else{
cardValue = new ArrayList<Integer>();
firstEntry.put(cardType,value);
cardValue.add(value);
mp.put(cardType, cardValue);
}
}
System.out.println();
int noOfSameCard=0,sumOfSameCard=0;
for(Map.Entry getData : mp.entrySet()){
System.out.println("\nCards with '" + getData.getKey() + "' Symbol : ");
ArrayList<Integer> symbolArray = (ArrayList<Integer>)
getData.getValue();
Iterator itr= symbolArray.iterator();
while(itr.hasNext()){
noOfSameCard++;
int num = (int) itr.next();
sumOfSameCard += num;
}
System.out.println("Number of Cards : " + noOfSameCard);
System.out.println("Sum of Values of Card Type '"+getData.getKey()+"'is:
"+ sumOfSameCard);
sumOfSameCard = 0;
noOfSameCard = 0;
}
System.out.println("");
System.out.println("First Entry of Each Card Type.");
for(Map.Entry getData : firstEntry.entrySet()){
System.out.println(getData.getKey() + " -> "+getData.getValue());
}
}
}
Output: