How to Write a Program in Java That Inputs N Words (String) & Outputs Them in Alphabetical Order
It can be helpful to sort a list of names into alphabetical order so that you can display them in an intuitive way to program users. It's also easier to search through alphabetically-ordered lists with Java algorithms. One way to sort names stored as strings is to place them in a Java array, and then use its built-in "sort" method to organize strings, such as "zz, yy, bb" into "bb, yy, zz."
Instructions
-
-
1
Open the Java file in an editor, such as Eclipse, Netbeans or JBuilder X.
-
2
Declare an array of string and add the names by adding the code:
"String [] names = new String[] { "luke", "bob", "jennifer" };."
-
-
3
Sort the names by adding the code: "Arrays.sort(names);." The "sort" method arranges the array in ascending order, which for strings corresponds to alphabetical order.
-
4
Output the sorted names by adding the code:
"System.out.println(Arrays.toString(names))". Using the previous example, it will display "[bob, jennifer, luke]."
-
5
Save the Java file, compile and run the program to view the outputted names in alphabetical order.
-
1