0% found this document useful (0 votes)
7 views3 pages

20BCS1793 Java 2.1

Uploaded by

ginolav365
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

20BCS1793 Java 2.1

Uploaded by

ginolav365
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment No :- 2.

NAME – Lakshay Kumar


UID – 20BCS1793
SECTION – 20BCS703-A
SUBJECT – PROJECT BASED LEARNING IN JAVA LAB

Aim/Overview of the practical:


Collect Unique Symbols From Set of Cards

Task to be done/ Which logistics used:


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.

Code:
Card.java

public class Card implements Comparable<Card> {


private char symbol;
private int number;

public Card() {}

public Card(char symbol, int number) {


super();
this.symbol = symbol;
this.number = number;
}

public char getSymbol() {


return symbol;
}

public void setSymbol(char symbol) {


this.symbol = symbol;
}

public int getNumber() {


return number;
}
public void setNumber(int number) {
this.number = number;
}

public String toString() {


return "Card [symbol=" + symbol + ", number=" + number + "]";
}

public int compareTo(Card o) {


if (this.symbol < o.symbol) return -1;
else if (this.symbol > o.symbol) return 1;
else return 1;
}

public int hashCode() {


return String.valueOf(symbol).hashCode();
}

public boolean equals(Object obj){


if (obj instanceof Card) {
Card card = (Card) obj;
return (card.symbol == this.symbol);
} else {
return false;
}
}
}
Test.java

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class TestMain {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Set<Card> set = new HashSet<>();

for (int i = 0; i < 8; i++) {


System.out.println("Enter a card:");
Card card = new Card();

card.setSymbol(sc.nextLine().charAt(0));
card.setNumber(sc.nextInt());
sc.nextLine();
set.add(card);
}

System.out.println("Cards in Set are:");

for (Card card : set)


System.out.println(card.getSymbol() + " " + card.getNumber());

sc.close();
}

Output:

You might also like