Need help with my java homework ASAP Thank you Write a progr
Need help with my java homework. ASAP Thank you
Write a program that asks a user to enter in two words. The program prints a string consisting of the characters that are common to both the words (letters that are in both words). [You should look up the String method index of (char) in the Java API documentation to help you.] Repeated letters must be counted only once, and the order of common letters is not important. For example, if the Strings are abbcd. and .ceccaa the value of the String returned by the method would be ac (order of characters not significant). Use a for loop. See Sample output below. You should have at least 3 test cases (different from the samples). Sample output://Shows when two words have common letters [----jGRASP exec: java Assign2_equals Enter two words: abccd ceccaa Common Letters are: ac ----jGRASP: operation complete.//shows when two words have no letters in common ----jGRASP exec: java Assign2_equals Enter two words: ghij abbcc No Common Letters: ac jGRASP: operation complete.Solution
import java.util.Scanner;
public class CommonLetters {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print(\"Enter two words: \");
String str1 = scanner.next();
String str2 = scanner.next();
String commonChars = getCommonChars(str1, str2);
if (commonChars.equals(\"\")) {
System.out.println(\"No Common Letters!\");
} else {
System.out.println(\"Common Letters are:\" + commonChars);
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* METHOD TO FIND THE COMMON CHARACTERS
*
* @param str1
* @param str2
* @return
*/
public static String getCommonChars(String str1, String str2) {
String commonStr = \"\";
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if (!commonStr.contains(str1.charAt(i) + \"\"))
commonStr += \"\" + str1.charAt(i);
}
}
}
return commonStr;
}
}
OUTPUT 1:
Enter two words: abccd ceccaa
Common Letters are:ac
OUTPUT 2:
Enter two words: ghij abbcc
No Common Letters!

