Sorting Strings in Ascending Order


/ Published in: Java
Save to your folder(s)

Strings are sorted in ascending order.

This was created by me in order to thwart Dr. McCloskey's evil ways of forcing CS majors to manually alphabetize lists of names and months.


Copy this code and paste it in your HTML
  1. import java.util.*;
  2.  
  3. public class SortName{
  4. public static void main(String[] argsv){
  5. Scanner s = new Scanner(System.in);
  6. System.out.print("How many data items do you wish to enter: ");
  7. int num = new Integer(s.nextLine()).intValue();
  8. String[] names = new String[num];
  9. System.out.println();
  10. int i = 0;
  11. while(i < num){
  12. names[i] = s.nextLine();
  13. i++;
  14. }
  15. StringComparator strcomp = new StringComparator();
  16. Arrays.sort(names, strcomp);
  17. for (String name: names){
  18. System.out.println(name);
  19. }
  20. }
  21. }
  22.  
  23. class StringComparator implements Comparator<String>{
  24. public int compare(String a, String b){
  25. return a.compareTo(b);
  26. }
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.