Q:

Write a Java Program to Sort Names in an Alphabetical Order

belongs to collection: Array Programs in Java with Examples

0

Write a Java Program to Sort Names in an Alphabetical Order

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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..

import java.util.Scanner;
public class Javaexcercise
{
    public static void main(String[] args) 
    {
        int num;
        String temp;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter number of names you want to enter:");
        num = s.nextInt();
        String names[] = new String[num];
        Scanner s1 = new Scanner(System.in);
        System.out.println("Enter all the names:");
        for(int i = 0; i < num; i++)
        {
            names[i] = s1.nextLine();
        }
        for (int i = 0; i < num; i++) 
        {
            for (int j = i + 1; j < num; j++) 
            {
                if (names[i].compareTo(names[j])>0) 
                {
                    temp = names[i];
                    names[i] = names[j];
                    names[j] = temp;
                }
            }
        }
        System.out.print("Names in Sorted Order:");
        for (int i = 0; i < num - 1; i++) 
        {
            System.out.print(names[i] + ",");
        }
        System.out.print(names[num - 1]);
    }
}

Result:

Enter number of names you want to enter: 5

Enter all the names: 

Sophia

Emma

Olivia

Emily

Mia

Names in Sorted Order: Emily, Emma, Mia, Olivia, Sophia

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Array Programs in Java with Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java Program to Display Transpose Matrix... >>
<< Write a Java Program to Sort the Array in Descendi...