HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Anagram Checking

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkinganagramstackoverflow

Problem

public class AnagramNumber {

    public static void checkAnagram(String[] str)
    {   
        String[] sortedArray=new String[str.length];
        for(int i=0;icharArray[i])
                {
                    temp=charArray[j];
                    charArray[j]=charArray[i];
                    charArray[i]=temp;
                }   

            }
            System.out.println(Arrays.toString(charArray));
        }

        return charArray;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String[] str={"hello","helol","elloh"};

        checkAnagram(str);

    }
}


Please review program and provide the best practices and feedback on code optimizing.

Solution

Besides what others have mentioned:

-
System.out.println in your sorting method just confused me. Either inform what exactly you are logging or remove it entirely. Preferably remove it.

-
Speaking of removing, your sorting method can be replaced by a call to Arrays.sort(strToCharArray);

char[] strToCharArray = str[i].toCharArray();
Arrays.sort(strToCharArray);
sortedArray[i] = new String(strToCharArray);


-
Make your checkAnagram method (which should be renamed to verifyIsOnlyAnagrams or something similar) more flexible by returning the value of flag instead of outputting the result.

boolean flag = true;
for (int j = 0; j < sortedArray.length - 1; j++) {
    ...
}

return flag;


And then let the main method deal with the output:

public static void main(String[] args) {
    String[] str={"hello","helol","elloh"};
    if (verifyIsOnlyAnagram(str)) {
        System.out.println(...);
    }
    else {
        System.out.println(...);
    }
}

Code Snippets

char[] strToCharArray = str[i].toCharArray();
Arrays.sort(strToCharArray);
sortedArray[i] = new String(strToCharArray);
boolean flag = true;
for (int j = 0; j < sortedArray.length - 1; j++) {
    ...
}

return flag;
public static void main(String[] args) {
    String[] str={"hello","helol","elloh"};
    if (verifyIsOnlyAnagram(str)) {
        System.out.println(...);
    }
    else {
        System.out.println(...);
    }
}

Context

StackExchange Code Review Q#45954, answer score: 7

Revisions (0)

No revisions yet.