I am new to the forum ( as a registered user ), so I tried really hard ( I swear! ) not to post a question, and look for old answers, and I checked other people's mistakes in problems similar to mine but I couldn't fine anything.
My code, downhere, is supposed to check if a word is an anagram of another or not. I am pretty sure I have complicated my life a lot and there would have been easier ways to do it but... I have been working on this for some time now and would like to see it work...
Any idea why it doesn't?
All I see is empty dictionaries and the two words are always anagrams when they have the same number of letters ( meaning that in fact my dictionaries aren't doing anything :'( )
import acm.program.ConsoleProgram;
import java.util.*;
public class Anagrams extends ConsoleProgram {
String firstWord;
String secondWord;
public boolean checkLength(String firstWord, String secondWord) {
if (firstWord.length() == secondWord.length()) {
println("Same length!");
return true;
} else {
return false;
}
}
public boolean anagram(String firstWord, String secondWord) {
firstWord = firstWord.toLowerCase();
secondWord = secondWord.toLowerCase();
String[] firstArray = firstWord.split("\\a");
String[] secondArray = secondWord.split("\\a");
int firstLength = firstWord.length();
int secondLength = secondWord.length();
Map<String, Integer> firstDictionary = new HashMap<String, Integer>();
Map<String, Integer> secondDictionary = new HashMap<String, Integer>();
for (firstLength = 0; firstLength == firstArray.length; firstLength++) {
System.out.println("checking the letter " + firstArray[firstLength] + " in array" + firstArray.toString());
if (firstDictionary.get(firstArray[firstLength]) == null) {
firstDictionary.put(firstArray[firstLength], 1);
} else {
firstDictionary.put(firstArray[firstLength], firstDictionary.get(firstArray[firstLength]) + 1);
}
}
for (secondLength = 0; secondLength == secondArray.length; secondLength++) {
if (secondDictionary.get(secondArray[secondLength]) == null) {
secondDictionary.put(secondArray[secondLength], 1);
} else {
secondDictionary.put(secondArray[secondLength], secondDictionary.get(secondArray[secondLength]) + 1);
}
}
if (firstDictionary.equals(secondDictionary)) {
return true;
} else {
return false;
}
}
public void run() {
int runAgain = 0;
while (runAgain == 0) {
println("Enter the first word to be analyzed");
firstWord = readLine();
println("Enter the second word to be analyzed");
secondWord = readLine();
if (checkLength(firstWord, secondWord) == true) {
if (anagram(firstWord, secondWord) == true) {
println("Yes! The two words are anagrams!");
}
} else {
println("No. The two words are not anagrams!");
}
}
}
}