Jiggy Palconit
Jiggy Palconit

Reputation: 51

HashSet Count Comparison Java

What I want to achieve is to count the numbers of the string that has the same value from the inputs.

Scanner reader = new Scanner(System.in);

Set group1 = new HashSet();
Set group2 = new HashSet();
Set self = new HashSet();

for (int i = 1; i <= 3; i++) {
    System.out.print("Enter birt month " + i + ": ");
    group1.add(reader.next());
}

for (int i = 1; i <= 3; i++) {
    System.out.print("Enter birt month " + i + ": ");
    group2.add(reader.next());
}
System.out.print("Enter your birth month: ");
self.add(reader.next());

if (group1.contains(self) || group2.contains(self)) {
    count++;
}
System.out.println("You have the same birth month with " + count + " of your classmate.");

But I didn't get the value that I should have, what I've got is that even though the group1 or group2 has the same value as the HashSet named self the counter doesn't goes up, it stays 0 and i don't know why. Any tips or please help me how to do this. Also I tried to vice versa the if statement into self.contains(group1) || self.contains(group2); to determine whether the self has the same group1 or group2

SOLVED!!

All I need was just to use containsAll which will read the set if group1 and group2 has it in the set named self

Upvotes: 1

Views: 327

Answers (2)

B Sangappa
B Sangappa

Reputation: 574

Also, One more issue I found is, your incrementing count variable only once if. What I would suggest is, use 2 if conditions like below,

    int count = 0;
    if (group1.containsAll(self)) {
        count++;
    }

    if (group2.containsAll(self)) {
        count++;
    }

The above condition takes care if both Set's had "self"

Upvotes: 2

Phenomenal One
Phenomenal One

Reputation: 2587

So, your problem is this.

group1.contains(self) checks if an object self is present inside group1 which is not the case here.

Here, you want to compare it to a Set self which is a Collection.

Change group1.contains(self) to group1.containsAll(self).

Upvotes: 2

Related Questions