-2

I´m a bloody beginner trying to write a lil programm to check if 2 words are anagrams. So far all the whitespaces within the words get deleted but apparently there's an error with my Arrays.sort() but I can´t see it. Why and where´s the error in my Arrays.sort() line and how could I solve it?

Edit: If I leave the Arrays.sort() out like this it compiles and works so apparently there's only a problem with that line. If I leave them in it points to array and says error: can not find symbol

public static void isAnagramm(String wordOne, String wordTwo)       
{

    String  w1= wordOne.replaceAll("\\s", ""); 
    int word1 = w1.length();
    String w2 = wordTwo.replaceAll("\\s", "");
    int word2 = w2.length();

    boolean anagrammStatus = false;



    if(word1 == word2)
    {
        anagrammStatus = true;
    }
    else
    {
        char [] charArrayWordOne = w1.toLowerCase().toCharArray(); 
        char [] charArrayWordTwo = w2.toLowerCase().toCharArray();  

        //Arrays.sort(charArrayWordOne); 
        //Arrays.sort(charArrayWordTwo);

        anagrammStatus = charArrayWordOne.equals(charArrayWordTwo);

    }

    if(anagrammStatus == false)
    {
        System.out.println("Anagram");
    }                   
    else;
    {
        System.out.println("No Anagram");
    }

}
grlpwr
  • 1
  • 2

1 Answers1

0

This should do the trick:

  public static void isAnagramm(String wordOne, String wordTwo)       
  {   
    String w1= wordOne.replaceAll("\\s", "");
    String w2 = wordTwo.replaceAll("\\s", "");

    // No need to keep the length variables

    boolean anagramStatus = false;

    // Check if the strings are equal to begin with, use equals and not  == operator
    if(w1.equals(w2)) 
    {
      anagramStatus = true;
    }
    else
    {
      char [] charArrayWordOne = w1.toLowerCase().toCharArray();
      char [] charArrayWordTwo = w2.toLowerCase().toCharArray();  

      Arrays.sort(charArrayWordOne);
      Arrays.sort(charArrayWordTwo);

      // Compare arrays using the Arrays.equals method to avoid comparing the object references
      anagramStatus = Arrays.equals(charArrayWordOne, charArrayWordTwo);
    }

    // Use simple boolean logic in your condition here, or again, always use == instead of =
    if (anagramStatus) 
    {
      System.out.println("Anagram");
    }                   
    else
    {
      System.out.println("No Anagram");
    }       
  }
TheWhiteRabbit
  • 1,253
  • 1
  • 5
  • 18
  • Thank you but even if I try to compile it now shows me not only an errors with Arrays.sort() but also with Arrays.equals(). In both cases it says error: can not find symbol – grlpwr Apr 26 '19 at 13:40
  • That's because you need to import the Arrays class, add following line at the top of your file: import java.util.Arrays; – TheWhiteRabbit Apr 26 '19 at 13:45