Wrote this program to find if 2 phrases are Anagrams of one another. Works except that I need to make it ignore any other character than letters(including spaces)

As is now I get 4 errors, all in that last boolean
1&2: cannot find symbols for phrase1/2.length (tried anag.phrase and didnt work)
3&4: char cannot be dereferenced (where its making p1array & p2array)

Thanks ahead of timee

public class Anagram
{
	private String phrase1;
	private String phrase2;
	private char p1array[];
	private char p2array[];

	public static void main (String[]arg)
	{
		Anagram anag = new Anagram();
		anag.phrase1 = arg[0];
		anag.phrase2 = arg[1];

		anag.phrase1 = letterchange(anag.phrase1);
		anag.phrase2 = letterchange(anag.phrase2);

		if (anag.isAnagram())
		{
			System.out.println(anag.phrase1+" is an anagram of "+anag.phrase2);
		}
		else
		{
			System.out.println(anag.phrase1+" is not an anagram of "+anag.phrase2);
		}
	
	}

	public static String letterchange(String phrase)
	{
		return phrase.toLowerCase();
	}

	//checks to see if all the letters are the same
	public boolean isAnagram()
	{		//get only letters from phrase1
			for (int j=0; j< phrase1.length; ++j)
			{
				if(Character.isLetter(j))
				{
					p1array = phrase2.charAt(j).toCharArray();
				}
			}
			//p1array = phrase1.toCharArray();
			java.util.Arrays.sort(p1array);
			
			//get only letters from phrase2
			for (int k=0; k< phrase2.length; ++k)
			{
				if(Character.isLetter(k))
				{
					p2array = phrase2.charAt(k).toCharArray();
				}
			}
			//p2array = phrase2.toCharArray();
			java.util.Arrays.sort(p2array);


			boolean equal = true; //sets equal initially to true

			if(p1array.length != p2array.length)
			{
				return false;
			}
			
			for (int i=0; i<p1array.length; ++i)
			{
				if(p1array[i] != p2array[i])
				{
					equal = false;
				}
			}
			return equal;
	}
}

Recommended Answers

All 3 Replies

Problems that I can see here, first in the code in line 38:

if(Character.isLetter(j))
{
   p1array = phrase2.charAt(j).toCharArray();
}

phrase2.charAt(j) results in a char, and there is no such thing as toCharArray() on char. The exact same problem occur in the if on line 49. Second problem is in the code on line 36:

for (int k=0; k< phrase2.length; ++k)

The variable phrase2 is a String, which means you have to use phrase2.length() and not phrase2.length .

is there a good method to go after solving the first problem then, I tried doing a little appending, as in if the character is a letter append it to the next and make a string but that does not work

i figured it out. I just did appending in the boolean and made a temporary new string from those appended characters, then sent those to character arrays

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.