Complete the method below that prints all elements that are in both Set s and Set t. Each matching element should be followed by a space. What can I change to make it work? import java.util.Set; import java.util.Iterator; public class Sets { public static void printMatches(Set s, Set t) { System.out.print("{ "); while(in.hasNext()){ String next = in.next(); { if((s.contains(next))&& (t.contains(next))){ System.out.print(next+" "); } } System.out.println("}"); } } import java.util.Set; import java.util.TreeSet; import java.util.Arrays; public class SetsTester { public static void main(String[] args) { Set set1 = new TreeSet<>(Arrays.asList("Bob", "Bill", "Sally")); Set set2 = new TreeSet<>(Arrays.asList("Sam", "Bob", "Frank")); Sets.printMatches(set1, set2); System.out.println("Expected: { Bob }"); Set set3 = new TreeSet<>(Arrays.asList("Sally", "Bill", "Frank")); Sets.printMatches(set1, set3); System.out.println("Expected: { Bill Sally }"); Sets.printMatches(set2, set3); System.out.println("Expected: { Frank }"); } }
Complete the method below that prints all elements that are in both Set<String> s and Set<String> t. Each matching element should be followed by a space.
What can I change to make it work?
import java.util.Set;
import java.util.Iterator;
public class Sets
{
public static void printMatches(Set<String> s, Set<String> t)
{
System.out.print("{ ");
while(in.hasNext()){
String next = in.next();
{
if((s.contains(next))&& (t.contains(next))){
System.out.print(next+" ");
}
}
System.out.println("}");
}
}
import java.util.Set;
import java.util.TreeSet;
import java.util.Arrays;
public class SetsTester
{
public static void main(String[] args)
{
Set<String> set1 = new TreeSet<>(Arrays.asList("Bob", "Bill", "Sally"));
Set<String> set2 = new TreeSet<>(Arrays.asList("Sam", "Bob", "Frank"));
Sets.printMatches(set1, set2);
System.out.println("Expected: { Bob }");
Set<String> set3 = new TreeSet<>(Arrays.asList("Sally", "Bill", "Frank"));
Sets.printMatches(set1, set3);
System.out.println("Expected: { Bill Sally }");
Sets.printMatches(set2, set3);
System.out.println("Expected: { Frank }");
}
}
Trending now
This is a popular solution!
Step by step
Solved in 5 steps with 3 images