java - Exception in program for search anagrams in 2 strings -
this question has answer here:
- how check if 2 words anagrams 37 answers
i have problem little program in java checks if 2 strings anagrams or not.
i stringindexoutofboundsexception
:
exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: 6 @ java.lang.string.charat(unknown source) @ areanagrams.areanagrams(areanagrams.java:9) @ areanagrams.main(areanagrams.java:30)
this code:
public class areanagrams { public static boolean areanagrams(string a, string b) { int j = 0; int = 0; if (a.length() == b.length()) { while (i < a.length()) { if (a.charat(i) == b.charat(j)) { j++; = 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")); } }
java.lang.stringindexoutofboundsexception
happens when refer character index exceeds string length.
for example string "dadmom" - when call charat(6)
, throw exception, because character indices in range 0 5.
you can use following code identify anagrams:
public static boolean areanagrams(string a, string b) { char[] achars = a.replaceall("\\s", "").tochararray(); char[] bchars = b.replaceall("\\s", "").tochararray(); arrays.sort(achars); arrays.sort(bchars); system.out.println(achars); system.out.println(bchars); return arrays.equals(achars, bchars); } public static void main(string[] args) { system.out.println(areanagrams("momdad", "dadmom")); }
Comments
Post a Comment