Advertisement
Guest User

Untitled

a guest
Oct 24th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. public class SuperAnTester {
  2.  
  3. public static void main(String[] args) {
  4. boolean again = true;
  5. String word1;
  6. String word2;
  7. SuperAnagram superAn;
  8. Scanner scan = new Scanner(System.in);
  9. System.out.println("Welcome to SuperAnagram Tester.");
  10. while(again)
  11. {
  12. System.out.println("Enter the first word:");
  13. word1 = scan.nextLine();
  14. System.out.println("Enter the second word:");
  15. word2 = scan.nextLine();
  16. superAn = new SuperAnagram(word1,word2);
  17. System.out.print("Result: ");
  18. System.out.println((superAn.testAnagram()) ? "Yes" : "No" );
  19. System.out.println("Enter \"Y\" to try another pair.8");
  20. String answer = scan.nextLine();
  21. if(!answer.toLowerCase().equals("y"))
  22. {
  23. again = false;
  24. System.out.print("Exiting SuperAnagram Tester.");
  25. }
  26. }
  27. scan.close();
  28. }
  29.  
  30. }
  31.  
  32. -----------------------------------------------------------------------------------------
  33. public class SuperAnagram
  34. {
  35. private String word1;
  36. private String word2;
  37.  
  38. public SuperAnagram(String word1, String word2)
  39. {
  40. this.word1 = word1;
  41. this.word2 = word2;
  42. }
  43.  
  44. public boolean testAnagram()
  45. {
  46. boolean result = true;
  47. word1 = word1.replaceAll("[^a-zA-Z]", "").toLowerCase();
  48. word2 = word2.replaceAll("[^a-zA-Z]", "").toLowerCase();
  49. String[] word1Letters = word1.split("");
  50. String[] word2Letters = word2.split("");
  51. Hashtable<String, Integer> processed = new Hashtable<String, Integer>();
  52.  
  53. for(String letter : word1Letters)
  54. {
  55. if(!word2.contains(letter))
  56. {
  57. result = false;
  58. break;
  59. }
  60. if(processed.containsKey(letter))
  61. {
  62. int timesSeen = processed.get(letter);
  63. timesSeen++;
  64.  
  65. int count = 0;
  66. for(String w2letter : word2Letters)
  67. {
  68. if(w2letter.equals(letter))
  69. {
  70. count++;
  71. }
  72. }
  73. if(timesSeen > count)
  74. {
  75. result = false;
  76. break;
  77. }
  78. processed.put(letter, timesSeen);
  79. }
  80. else
  81. {
  82. processed.put(letter, 1);
  83. }
  84. }
  85. return result;
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement