22BCS16851 Muskan Soni Java 4
22BCS16851 Muskan Soni Java 4
1. Aim: Create a program to collect and store all the cards to assist the
users in finding all the cards in a given symbol using Collection
interface.
2. Implementation:
import java.util.*;
public class CardCollection {
private List<String> cards; // Use a List to store the cards
public CardCollection() {
cards = new ArrayList<>();
}
public void addCard(String card) {
cards.add(card);
}
public List<String> findCardsBySymbol(String symbol) {
List<String> matchingCards = new ArrayList<>();
for (String card : cards) {
if (card.contains(symbol)) { // Check if the card contains the symbol
matchingCards.add(card);
}
}
return matchingCards;
}
public void displayAllCards() {
if (cards.isEmpty()) {
System.out.println("No cards in the collection yet.");
} else {
System.out.println("All Cards in the Collection:");
for (String card : cards) {
System.out.println(card);
}
}
}
public static void main(String[] args) {
CardCollection collection = new CardCollection();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nCard Collection Menu:");
System.out.println("1. Add Card");
System.out.println("2. Find Cards by Symbol");
System.out.println("3. Display All Cards");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter the card details (e.g., 'Ace of Spades'): ");
String card = scanner.nextLine();
collection.addCard(card);
System.out.println("Card added.");
break;
case 2:
System.out.print("Enter the symbol to search for (e.g., 'Spades'): ");
String symbol = scanner.nextLine();
List<String> foundCards = collection.findCardsBySymbol(symbol);
if (foundCards.isEmpty()) {
System.out.println("No cards found with that symbol.");
} else {
System.out.println("Cards with symbol '" + symbol + "':");
for (String foundCard : foundCards) {
System.out.println(foundCard);
}
}
break;
case 3:
collection.displayAllCards();
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
3. Output:
4. Learning outcomes:
• Collections Framework: Using the List interface (specifically ArrayList) to store and
manage a collection of cards.
• Object-Oriented Programming: Designing a class (CardCollection) to represent and
manage the card collection.
• String Manipulation: Using the contains() method to search for cards based on a
symbol within their string representation.
• Data Structures: Understanding how a List works and why it's suitable for this task.
• User Interaction: Creating a menu-driven program to interact with the user and perform
actions on the card collection.