-2

I just would like to ask what is wrong regarding my code for it does not output that the 2 words are anagram. Appreciate any help thanks.

public class Program {

public static void main(String[] args){
    String word1 ="test";
    String word2 = "tset";
    boolean output = isAnagram(word1,word2);
    System.out.println("isAnagram:"+output);
}

public static boolean isAnagram(String word1, String word2){ 
       boolean output = false;
       boolean found = false;
       int x = 0;
       int ctr = 0;
          for(int i=0; i<word1.length()-1;i++){

          x=0;
          found=false;

          while(found!=true){
              if(word1.charAt(x)==word2.charAt(i)){
                  ctr++;
                  found=true;
              }

              else{

                  x++;
              }
          }}
       if(ctr==word1.length()&&ctr==word2.length()){
           output = true;
       }
        return output;
    }}   
Snail
  • 57
  • 1
  • 1
  • 3
  • possible duplicate of [Anagram algorithm in java](http://stackoverflow.com/questions/13692221/anagram-algorithm-in-java) – ka4eli Aug 05 '15 at 20:40
  • 1
    We are not here to GUESS what MIGHT be wrong with your code, especially if you can't be bothered to explain HOW it isn't working properly. – Marc B Aug 05 '15 at 20:40
  • [It looks like this question has what you're looking for](http://stackoverflow.com/questions/15045640/how-to-check-if-two-words-are-anagrams) – fear7 Aug 05 '15 at 20:43

1 Answers1

0
public static boolean isAnagram(String word1, String word2){ 

   boolean isAnagram = false;
   int x = 0;
   int ctr = 0;
    if(word1.length() == word2.length()){
    int n = 0;
    for(int c = word2.length(); c > 0 && n < word2.length() , c++ ){
if(word1.charAt(n).equals(word2.charAt(c))){
x++;
}
n++;
}
if(x == word1.length())
isAnagram == true;
}  
    return isAnagram;
}}   

this takes the first and last letters or chars and counts down on the second one and counts up on the second one.

Max Fortin
  • 125
  • 1
  • 11