Program to read N different strings from user and sort it in Java

 



Code:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of string you want to sort: ");
        int n = sc.nextInt();
                
        String str[] = new String[n];
        String temp;
        int i, j;
        
        System.out.println("Enter all strings:");
        for(i = 0; i < str.length; i++)
        {
            str[i] = sc.next();
        }
        
        for(i = 0; i < str.length; i++)
        {
            for(j = i + 1; j < str.length; j++)
            {
                if((str[i].compareTo(str[j])) > 0)
                {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }
        System.out.println("\nSorted strings:");
        for(i = 0; i < str.length; i++)
        {
            System.out.println(str[i]);
        }
    }
}


Output:

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page