The problem
Write a program that asks the user to enter three names, and then display the name sorted in ascending order. For example if the user enterd "Charlie" , "Leslie" , and "Andy", the program would display:
- Andy
- Charlie
- Leslie
Breaking it down
Create variables
// collection to hold names
List<String> names = Lists.newArrayList();
// scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
String name;
Ask user for input
// Get the user's selection.
do {
System.out.print("Enter name (-1 to exit): ");
name = keyboard.next();
if (!name.equals("-1")) {
names.add(name);
}
} while (!name.equals("-1"));
Sort collection
Collections.sort(names);
Display names
for (String name2 : names) {
System.out.println(name2);
}
Output
Enter name (-1 to exit): Jack
Enter name (-1 to exit): Sally
Enter name (-1 to exit): Tim
Enter name (-1 to exit): Billy
Enter name (-1 to exit): Allan
Enter name (-1 to exit): -1
Allan
Billy
Jack
Sally
Tim
Level Up
- Enhance program to include the amount of time it took to sort names
- Enhance output with a column heading
- Display whether or not the names are already sorted