Note that there are some explanatory texts on larger screens.

plurals
  1. POOdd comparison problem in checking for anagram
    primarykey
    data
    text
    <p>I'm sorry, the title's awful; however, I couldn't think of any better way to summarize my plight.</p> <p>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.</p> <p>If so, the program prints out "Is an anagram.", otherwise "Is not an anagram."</p> <p>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.</p> <p>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.</p> <p>Here's the code:</p> <pre><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&gt;"); test1 = input.nextLine().replaceAll(" ", "").toCharArray(); Arrays.sort(test1); System.out.print("Enter second phrase&gt;"); 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)); } } </code></pre> <p>And the resulting output from a test run:</p> <pre><code>Enter first phrase&gt;CS AT WATERLOO Enter second phrase&gt;COOL AS WET ART Is not an anagram. AACELOORSTTW AACELOORSTTW false </code></pre> <p>Any and all help is greatly appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload