Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SuperAnTester {
- public static void main(String[] args) {
- boolean again = true;
- String word1;
- String word2;
- SuperAnagram superAn;
- Scanner scan = new Scanner(System.in);
- System.out.println("Welcome to SuperAnagram Tester.");
- while(again)
- {
- System.out.println("Enter the first word:");
- word1 = scan.nextLine();
- System.out.println("Enter the second word:");
- word2 = scan.nextLine();
- superAn = new SuperAnagram(word1,word2);
- System.out.print("Result: ");
- System.out.println((superAn.testAnagram()) ? "Yes" : "No" );
- System.out.println("Enter \"Y\" to try another pair.8");
- String answer = scan.nextLine();
- if(!answer.toLowerCase().equals("y"))
- {
- again = false;
- System.out.print("Exiting SuperAnagram Tester.");
- }
- }
- scan.close();
- }
- }
- -----------------------------------------------------------------------------------------
- public class SuperAnagram
- {
- private String word1;
- private String word2;
- public SuperAnagram(String word1, String word2)
- {
- this.word1 = word1;
- this.word2 = word2;
- }
- public boolean testAnagram()
- {
- boolean result = true;
- word1 = word1.replaceAll("[^a-zA-Z]", "").toLowerCase();
- word2 = word2.replaceAll("[^a-zA-Z]", "").toLowerCase();
- String[] word1Letters = word1.split("");
- String[] word2Letters = word2.split("");
- Hashtable<String, Integer> processed = new Hashtable<String, Integer>();
- for(String letter : word1Letters)
- {
- if(!word2.contains(letter))
- {
- result = false;
- break;
- }
- if(processed.containsKey(letter))
- {
- int timesSeen = processed.get(letter);
- timesSeen++;
- int count = 0;
- for(String w2letter : word2Letters)
- {
- if(w2letter.equals(letter))
- {
- count++;
- }
- }
- if(timesSeen > count)
- {
- result = false;
- break;
- }
- processed.put(letter, timesSeen);
- }
- else
- {
- processed.put(letter, 1);
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement