I have a problem with this little program in Java for which checks if 2 strings are anagrams or not.
I get a StringIndexOutOfBoundsException
:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(Unknown Source)
at AreAnagrams.areAnagrams(AreAnagrams.java:9)
at AreAnagrams.main(AreAnagrams.java:30)
This is my code:
public class AreAnagrams {
public static boolean areAnagrams(String a, String b) {
int j = 0;
int i = 0;
if (a.length() == b.length()) {
while (i < a.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
i = 0;
} else {
i++;
if (j > a.length()) {
return false;
}
}
}
} else {
return false;
}
return false;
}
public static void main(String[] args) {
System.out.println(areAnagrams("momdad", "dadmom"));
}
}