I have a program which has the user inputs a list of names. I have a switch case going to a function which I would like to have the names print off in alphabetical order.
By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.
I would suggest to have a class implement compare method of Comparator-interface as :
public int compare(Object o1, Object o2) {
return o1.toString().compareToIgnoreCase(o2.toString());
}
and from the calling method invoke the Arrays.sort method with custom Comparator as :
Arrays.sort(inputArray, customComparator);
Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"
output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani
Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep
Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.
for more understanding of natural and alphabetical/lexical order visit discussion here
**//With the help of this code u not just sort the arrays in alphabetical order but also can take string from user or console or keyboard
import java.util.Scanner;
import java.util.Arrays;
public class ReadName
{
final static int ARRAY_ELEMENTS = 3;
public static void main(String[] args)
{
String[] theNames = new String[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the names: ");
for (int i=0;i<theNames.length ;i++ )
{
theNames[i] = keyboard.nextLine();
}
System.out.println("**********************");
Arrays.sort(theNames);
for (int i=0;i<theNames.length ;i++ )
{
System.out.println("Name are " + theNames[i]);
}
}
}**
public static String[] textSort(String[] words) {
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (words[i].compareTo(words[j]) > 0) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
return words;
}
CompareTo()
method: The two strings are compared based on Unicode character values.
import java.util.*;
public class Test {
int n,i,temp;
String names[n];
public static void main(String[] args) {
String names[5] = {"Brian","Joshua","Louis","David","Marcus"};
for(i=0;i<5;i++){
for(j=i+1;i<n;j++){
if(names[i].CompareTo(names[j]>0) {
temp=names[i];
names[i]=names[j];
names[j]=temp;
} else
System.out.println("Alphabetically Ordered");
}
}
}
Weird, your code seems to work for me:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
// args is the list of guests
Arrays.sort(args);
for(int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
I ran that code using "java Test Bobby Joe Angel" and here is the output:
$ java Test Bobby Joe Angel
Angel
Bobby
Joe