*4.24 (Order three cities) Write a program that prompts the user to enter three cities and
displays them in ascending order. Here is a sample run:
Enter the first city: Chicago
Enter the second city: Los Angeles
Enter the third city: Atlanta
The three cities in alphabetical order are Atlanta Chicago Los Angeles
Enter the first city: Chicago
Enter the second city: Los Angeles
Enter the third city: Atlanta
The three cities in alphabetical order are Atlanta Chicago Los Angeles
import java.util.Scanner; public class ProgrammingEx4_24 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the first city:"); String first = input.nextLine(); System.out.print("Enter the second city:"); String second = input.nextLine(); System.out.print("Enter the third city:"); String third = input.nextLine(); String temp = ""; if (first.compareTo(second) > 0) { temp = second; second = first; first = temp; } if (second.compareTo(third) > 0) { temp = third; third = second; second = temp; } if (first.compareTo(second) > 0) { temp = second; second = first; first = temp; } System.out.println("The three cities in alphabetical order are " + first + " " + second + " " + third); } }
No comments:
Post a Comment