Java program that reads in three strings and sorts them lexicographically
Posted by Samath
Last Updated: May 08, 2021

Write a program that reads in three strings and sorts them lexicographically.
     Enter a string: Charlie
     Enter a string: Able
     Enter a string: Baker
     Able
     Baker
     Charlie

Code:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter First String: ");
		String s1 = input.next();
		System.out.print("Enter Second String: ");
		String s2 = input.next();
		System.out.print("Enter Third String: ");
		String s3 = input.next();
		input.close();
		
		if (s1.compareTo(s2) < 0 && s1.compareTo(s3) < 0) {
			System.out.println(s1);
			if (s2.compareTo(s3) < 0) {
				System.out.println(s2);
				System.out.println(s3);
			} else {
				System.out.println(s3);
				System.out.println(s2);
			}
		} else if (s1.compareTo(s2) > 0 && s2.compareTo(s3) < 0) {
			System.out.println(s2);
			if (s1.compareTo(s3) < 0) {
				System.out.println(s1);
				System.out.println(s3);
			} else {
				System.out.println(s3);
				System.out.println(s1);
			}
		} else {
			System.out.println(s3);
			if (s1.compareTo(s2) < 0) {
				System.out.println(s1);
				System.out.println(s2);
			} else {
				System.out.println(s2);
				System.out.println(s1);
			}
		}
	}
}