I'm sorry, the title's awful; however, I couldn't think of any better way to summarize my plight.
In trying to solve a problem involving checking to see if one string is an anagram of another, I implemented a solution that involved removing all whitespace from both strings, converting them both to character arrays, sorting them and then seeing if they are equal to eachother.
If so, the program prints out "Is an anagram.", otherwise "Is not an anagram."
The problem is that even though my code compiles successfully and runs fine, the end result will always be "Is not an anagram.", regardless of whether or not the two original strings are indeed anagrams of each other. Quick code I inserted for debugging shows that, in a case with an actual anagram, the two character arrays I end up comparing are apparently identical, yet the result of the comparison is false.
I can't tell why exactly this is happening, unless I'm overlooking something incredibly obvious or there are some extra undisplayed characters in what I compare.
Here's the code:
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
char[] test1;
char[] test2;
Scanner input = new Scanner(System.in);
System.out.print("Enter first phrase>");
test1 = input.nextLine().replaceAll(" ", "").toCharArray();
Arrays.sort(test1);
System.out.print("Enter second phrase>");
test2 = input.nextLine().replaceAll(" ", "").toCharArray();
Arrays.sort(test2);
if (test1.equals(test2)) {
System.out.println("Is an anagram.");
}
else {
System.out.println("Is not an anagram.");
}
/* debugging */
System.out.println(test1);
System.out.println(test2);
System.out.println(test1.equals(test2));
}
}
And the resulting output from a test run:
Enter first phrase>CS AT WATERLOO
Enter second phrase>COOL AS WET ART
Is not an anagram.
AACELOORSTTW
AACELOORSTTW
false
Any and all help is greatly appreciated.