Hello, I am working on a program that checks if two string are anagrams of each other. To those of you who don't know what an anagram is, it is simply two words in which you can rearrange the characters of one word to get the second word. Example: Dog, GdO.
My problem is that my program is picking up on 'Anagrams' even though it shouldn't and I stepped through my logic several time, and it makes complete sense to me.
More specifically, the if statements comparing one character to the other character are evaluating to true even though it shouldn't.
In other words I am 'asking' my program does 'g' == '4' and it says YES.
Note: I change the character of the wherever a match was found '4' (which is not a letter) that way, the next time the loop runs it wont pick up on the SAME match twice.
This is very frustrating, Any help will be greatly appreciated!
Can you post more code - Put this code in a context in which we can see where and when it is run, and can compile and run the code?
A couple of notes:
This is repetitive. If the first comparison is false then the second comparison must be true. So you should simplify the code, and make it just:
to avoid confusion and possible errors (less code is better. Duplication is bad.)
Your comparison for comparing case is not very good either. It doesn't take into affect non-cased characters. For example, if one character is '4' and the other is 'T' would pass the 'ignore case' comparison as equal. Perhaps a better approach would be to use the tools available in the Character class:
Your solution looks weird. I think you need to write down, in words of one syllable, how you are working out which words are anagrams of each other. Try it with three words (three there ether) and see if you can prove they are anagrams. Those three words once appeared in opposite corners of the Times crossword. There is somewhere in the Java™ Tutorials an exercise with a set of 11 anagrams, but I can't remember where.
Once you have worked out how to do it, then you can write the code.
A hint: consider an algorithm where you transform both words into another form, such that if those two other forms are equal, the words are anagrams. Such an algorithm would be vastly simpler than what you're trying to do here.