forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
46 lines (34 loc) · 1.3 KB
/
Copy pathAnagram.java
File metadata and controls
46 lines (34 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
String firstWord, secondWord;
int[] firstWordHist, secondWordHist;
boolean result;
Scanner input = new Scanner(System.in);
System.out.println("Let's find out if two words are anagrams.");
System.out.print("Please enter the first word: ");
firstWord = input.nextLine();
System.out.print("Please enter the second word: ");
secondWord = input.nextLine();
firstWordHist = createLetterHistogram(firstWord);
secondWordHist = createLetterHistogram(secondWord);
result = isAnagram(firstWordHist, secondWordHist);
System.out.print("Are " + firstWord + " and " + secondWord + " anagrams? ");
System.out.println(result);
}
public static int[] createLetterHistogram(String word) {
int[] wordHist;
wordHist = Ex2.letterHist(word);
return wordHist;
}
public static boolean isAnagram(int[] firstWordHist, int[] secondWordHist) {
boolean anagram = true;
for (int i = 0; i < firstWordHist.length; i++) {
if (firstWordHist[i] != secondWordHist[i]) {
anagram = false;
break;
}
}
return anagram;
}
}