Try this code.
String str1 = "heart";
String str2 = "earth";
boolean isNotAnagram = false;
if(str1.length() == str2.length()) {
int len = str1.length();
char ch1[] = str1.toCharArray();
char ch2[] = str2.toCharArray();
for(int i=0; i<len; i++){
for(int j=0; j><len; j++){
if( (ch1[i] == ch2[j]) && (ch1[i] != '#') ) {
ch1[i] = '#';
ch2[j] = '#';
}
}
}
for(int i=0; i><len; i++) {
if(ch2[i] != '#') {
isNotAnagram = true;
break;
}
}
if(isNotAnagram) System.out.println("Inputs are not anagrams");
else System.out.println("Inputs are anagrams");
}
else System.out.println("Inputs are not anagrams");
http://en.wikipedia.org/wiki/Anagram
Cheers.
Message was edited by:
astelaveesta>
Cool, thanks for the help.
I was actually able to get it last night
// The "Anagram" class.
import java.awt.*;
import hsa.Console;
public class Anagram
{
static Console c;// The output console
public static void main (String [] args)
{
c = new Console ();
// Place your program here. 'c' is the output console
c.println ("Enter the first word you want checked to see if its an anagram");
String word1 = c.readString ();
c.println ("Enter the second word you want checked to see if its an anagram");
String word2 = c.readString ();
testAnagramInter (word1, word2);
} // main method
public static void testAnagramInter (String word1, String word2)
{
int u = 0;
String word3 = "";
char [] wordA = new char [word1.length ()];
char [] wordB = new char [word2.length ()];
char tmp;
for (int x = 0 ; x <= 1 ; x++)
{
if (x == 0)
{
word3 = word1;
}
else
{
word3 = word2;
}
char [] word = new char [word3.length ()];
for (int ii = 0 ; ii < word3.length () ; ii++)
{
word [ii] = word3.charAt (ii);
}
for (int i = word3.length () - 1 ; i >= 0 ; i--)
{
for (int j = 1 ; j <= i ; j++)
{
if (word [j - 1] > word [j])
{
tmp = word [j - 1];
word [j - 1] = word [j];
word [j] = tmp;
}
if (x == 0)
{
wordA [i] = word [i];
}
else
{
wordB [i] = word [i];
}
}
}
for (int i = 0 ; i < word3.length () ; i++)
{
c.print (word [i]);
}
c.println ();
}
for (int z = 0 ; z <= word1.length () - 1 ; z++)
{
if (wordA [z] == wordB [z])
{
}
else if (word1.compareTo (word2) != 0)
{
u++;
}
}
if (u == 0)
{
c.println ("Anagram");
}
else
c.println ("Not an Anagram!");
}
} // Anagram class
I know it's long but it works, unfortunalty I couldn't figure out how to do it in recursion which was the next problem.
public class AnagramTester
{
public static void main(String[] args) {
AnagramTester at = new AnagramTester();
if (at.test("heart", "earth")) {
System.out.println("Anagrams!");
} else {
System.out.println("Not anagrams!");
}
}
public boolean test(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
char[] a1 = s1.toLowerCase().toCharArray();
char[] a2 = s1.toLowerCase().toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
return test(0, a1, a2);
}
private boolean test(int index, char[] a1, char[] a2) {
if (index == a1.length) {
return true;
}
if (a1[index] != a2[index]) {
return false;
}
return test(index + 1, a1, a2);
}
}