-2

Question: Write a method to sort an array of strings so that all the anagrams are next to each other.

I am trying to test the methods in the main. When I compile it gives me this error:

Error:(29, 28) java: non-static method sortChars(java.lang.String) cannot be referenced from a static context

How can I fix this error?

import java.util.Arrays;

import java.util.Comparator;

public class StringAnagrams implements Comparator{

public  String sortChars(String s){

    char[] content = s.toCharArray();
    Arrays.sort(content);

    return new String(content);
}

public  int compare(String s1, String s2){

    return sortChars(s1).compareTo(sortChars(s2));
}

public static void main (String [] args){


    String st1 = "tree";
    String st2 = "eert";

    System.out.println(sortChars(st1));
    System.out.println(sortChars(st2));

    System.out.println(compare(st1,st2));


}

}

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
Ehsan
  • 21
  • 2
  • 6

1 Answers1

1

you will need to add static keyword to your method.

public static String sortChars(String s){
char[] content = s.toCharArray();
Arrays.sort(content);

return new String(content);
}
omurbek
  • 742
  • 1
  • 7
  • 23