Write a Java Program to Sort Names in an Alphabetical Order


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise
  3. {
  4. public static void main(String[] args)
  5. {
  6. int num;
  7. String temp;
  8. Scanner s = new Scanner(System.in);
  9. System.out.print("Enter number of names you want to enter:");
  10. num = s.nextInt();
  11. String names[] = new String[num];
  12. Scanner s1 = new Scanner(System.in);
  13. System.out.println("Enter all the names:");
  14. for(int i = 0; i < num; i++)
  15. {
  16. names[i] = s1.nextLine();
  17. }
  18. for (int i = 0; i < num; i++)
  19. {
  20. for (int j = i + 1; j < num; j++)
  21. {
  22. if (names[i].compareTo(names[j])>0)
  23. {
  24. temp = names[i];
  25. names[i] = names[j];
  26. names[j] = temp;
  27. }
  28. }
  29. }
  30. System.out.print("Names in Sorted Order:");
  31. for (int i = 0; i < num - 1; i++)
  32. {
  33. System.out.print(names[i] + ",");
  34. }
  35. System.out.print(names[num - 1]);
  36. }
  37. }

Result

java techstudy.org

     





Related Topics




Popular Posts