Give a program segment that prompts the user for two English
Give a program segment that prompts the user for two English words, and displays which letters the two words have in common.
use set(s)
Solution
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String word1=\"\"; //string variable to store first word
String word2=\"\"; //string variable to store second word
//object to take input from the user
Scanner input=new Scanner(System.in);
//asking user to enter first word
System.out.println(\"Enter first english word :\");
//storing user entered first word in word1
word1=input.nextLine();
//asking user to enter second word
System.out.println(\"Enter second english word :\");
//storing user entered second word in word2
word2=input.nextLine();
//creating charac1 object of type ser for storing first word
Set<Character> charac1 = new TreeSet<Character>();
for(int i = 0; i < word1.length(); i++) {
//adding letters of word1 into set
charac1.add(word1.charAt(i));
}
//creating charac2 object of type ser for storing second word
Set<Character> charac2 = new TreeSet<Character>();
for(int i = 0; i < word2.length(); i++) {
//adding letters of word2 into set
charac2.add(word2.charAt(i));
}
//intersection of both set will give the common letters of both word
charac1.retainAll(charac2);
//printing common letters
System.out.println(\"Common letters in the two words : \"+charac1);
}
}
/***OUTPUT***********
Enter first english word :
treeset
Enter second english word :
settree
Common letters in the two words : [e, r, s, t]
****OUTPUT***********
/* Note:As there is no any langauge provided in the question i have written the code in java which has been tested on eclipse,Please do ask in case of any doubt,Thanks..*/
