I've completed a program that tests whether two words are anagrams. The program seems to work, but I was just wondering if there is anything I could be doing to make the code better. Everything is below, there is a main program and one class.
Main:
import java.util.Scanner;
public class StringTesting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
StringUtil object = new StringUtil();
String word1;
String word2;
System.out.print("Enter word one: ");
word1 = input.next();
System.out.print("Enter word two: ");
word2 = input.next();
if(object.isAnagram(word1, word2)){
System.out.println("It's an anagram!");
} else {
System.out.println("It's not an anagram.");
}
}
}
StringUtil Class:
public class StringUtil
{
public int countCharacters(String str, char ch)
{
int count = 0;
for(byte i = 0; i < str.length(); i++){
if(str.toLowerCase().charAt(i) == Character.toLowerCase(ch)){
count++;
}
}
return count;
}
public boolean isAnagram(String str1, String str2)
{
int count = 0;
if(str1.length() != str2.length()){
return false;
}
for(byte i = 0; i < str1.length(); i++){
char ch = str1.toLowerCase().charAt(i);
for(byte j = 0; j < str1.length(); j++){
char ch2 = str2.toLowerCase().charAt(j);
if(ch == ch2){
if(countCharacters(str1, ch) != countCharacters(str2, ch2)){
return false;
} else {
count++;
}
}
}
}
if(count == str1.length()){
return true;
} else {
return false;
}
}
}