0

The below code working without error but it not getting proper result for anagram. The if condition is return false for correct value.

import java.util.*;

public class Anagram{
    public boolean solve(String s1, String s2){
        if(s1.length() != s2.length()) return false;
        
        String[] s11 = s1.split("");
        String[] s12 = s2.split("");

        Arrays.sort(s11);
        System.out.println(Arrays.toString(s11));
        Arrays.sort(s12);
        System.out.println(Arrays.toString(s12));

        
        for(int i = 0; i < s1.length(); i++){
            if(s11[i] != s12[i])
             System.out.println(s11[i]);
             System.out.println(s12[i]);
             return false;
        }

        return true;
    }

    public static void main(String[] args){
        String s1 = "restful";
        String s2 = "fluster";

        Anagram v = new Anagram();

        if(v.solve(s1, s2)){
            System.out.println(s2 + " is anagram of the " + s1);
        }else{
            System.out.println("not an anagram");
        }
    }
}

Please let me know why it is not working

  • 4
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – OH GOD SPIDERS Mar 14 '22 at 12:38
  • 1
    `if(s11[i] != s12[i])` <- 1. Error is not using equals to compare the Strings, and 2. Error is that your if statement doesn't have braces `{...}`. So only `System.out.println(s11[i]);` is conditional and the `return false;` is not and will always be executed. – OH GOD SPIDERS Mar 14 '22 at 12:40

1 Answers1

0

Ideally here no need to check individual character from both the Array You can directly check both the Sorted Arrays are equals or not. Replace your for loop with the below code :

if(!Arrays.equals(s11, s12)){
        return false ;
}

Also your code is not working because == is comparing the reference and not the value in Java

drjansari
  • 306
  • 1
  • 11