Wednesday, 15 April 2015

STRING ARRAY

Write a program to store the given city names in a single dimension array. Sort these names in alphabetical order.
Input : Delhi, Bangalore, Agra, Mumbai, Calcutta
Output : Agra, Bangalore, Calcutta, delhi, Mumbai
Solution:-
import java.io.*;
public class eight
{
public static void main()throws IOException
{
    BufferedReader d=new BufferedReader(new InputStreamReader(System.in));
    String a[]={"Delhi","Bangalore","Agra","Mumbai","Calcutta"};
    String t=new String();
    for(int i=0;i<5;i++)
    {
        for(int j=i;j<5;j++)
        {
            if(a[i].compareTo(a[j])>0)
            {
                t=a[i];
                a[i]=a[j];
                a[j]=t;
            }
        }
    }
    for(int i=0;i<5;i++)
    {
       System.out.print(a[i]+" , ");
    }
   
}
}
Output
Agra, Bangalore, Calcutta, delhi, Mumbai
Variable Description

Variable
Type
Purpose
a[]
String object array
Storing five city names
t
String object
For use of swaping values
i
Integer
Counter Varable
J
Integer
Counter Varable

No comments:

Post a Comment