/* * SameSetOfWords * Read in two lines (sentences) from the user. * Determine if the two sentences use the same words, * regardless of punctuation, repeated words, and letter-case. * Parke Godfrey * 2009-11-10 */ import java.io.PrintStream; import java.util.Scanner; public class SameSetOfWords { public static void main(String[] args) { PrintStream output = System.out; Scanner input = new Scanner(System.in); output.println("Enter the first sentence:"); Scanner first = new Scanner(input.nextLine().toLowerCase()); output.println("Enter the second sentence:"); Scanner second = new Scanner(input.nextLine().toLowerCase()); String secondSen = ".."; for (; second.hasNext();) { secondSen += second.next().replaceAll("\\p{Punct}", "") + "."; } String firstSen = ".."; for (; first.hasNext();) { firstSen += first.next().replaceAll("\\p{Punct}", "") + "."; } // Every word of first is in second. int start = 0; int end = 1; boolean secondMissing = false; while ((start < firstSen.length() - 1) && !secondMissing) { end = firstSen.indexOf(".", start + 1); String word = firstSen.substring(start, end + 1); if (secondSen.indexOf(word) < 0) { secondMissing = true; } start = end; } // Every word of second is in first. start = 0; end = 1; boolean firstMissing = false; while ((start < secondSen.length() - 1) && !firstMissing) { end = secondSen.indexOf(".", start + 1); String word = secondSen.substring(start, end + 1); if (firstSen.indexOf(word) < 0) { firstMissing = true; } start = end; } if (!firstMissing && !secondMissing) { output.println("The words used are the same."); } else if (firstMissing && !secondMissing) { output.println("Word in second not in first."); } else if (!firstMissing && secondMissing) { output.println("Word in first not in second."); } else { output.println("Words in each not in the other."); } } }