Answer to Question #257506 in Java | JSP | JSF for Nikhil Sahoo

Question #257506

Write a program in Java to display the words of a string in alphabetical order from A to Z.


1
Expert's answer
2021-10-27T18:51:31-0400
import java.util.Scanner;

public class AtoZ {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        
        String line;
        System.out.println("Enter the string:");
        line=sc.nextLine();
        System.out.println("Entered string is:"+line);
        
        
        //split the entered string which contains the space between the words- (" ")
                String[] words = line.split(" ");
                String temp;
                
                // swap the words according to alphabetical order
                for(int i=0;i<words.length;i++){
                    for(int j=i+1;j<words.length;j++){
                        if(words[i].compareTo(words[j])>0){
                            temp=words[i];
                            words[i]=words[j];
                            words[j]=temp;
                            
                        }                        
                    }
                }
                System.out.print("The required string in the alphabetical order:");
                for (int i = 0; i < words.length; i++) {
                    System.out.println(words[i]);
                }
        }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS