java - Exception in program for search anagrams in 2 strings -


this question has answer here:

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

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -