In Java, Sorted ArrayList Of Names In Title Case

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main{
	static List<String> personNames = new ArrayList<String>();

	public static void main(String args[]){
		Scanner scanner = new Scanner(System.in);
		String inputName;
		while (true){
			System.out.println("Enter the next name:");
			inputName = scanner.nextLine().trim();
			if (inputName.toLowerCase().equals("end")){
				break;
			} else {
				insertionSort(titleCase(inputName));
			}

		}

		System.out.println(personNames.toString());
	}

	/**
	 * * It converts the given sting in titleCase.
	 * * @param name
	 * * @return
	 * */
	public static String titleCase(String name){
    final char[]all = name.toCharArray();
		StringBuilder s1 = new StringBuilder(all.length);
    boolean caps = true;
    for(char c : all){
      if(Character.isSpaceChar(c)){
        caps = true;
      } else if(caps){
        c = Character.toUpperCase(c);
        caps = false;
      } else {
        c = Character.toLowerCase(c);
      }
      s1.append(c);
    }
		return s1.toString();
	}

	/**
	 * * Insertion sort for String arraylist.
	 * * @param name
	 * */
	public static void insertionSort(String name)
	{
		final int len = personNames.size();
		for (int i = 0; len > i; i++){
			String s = personNames.get(i);
			if (0 > name.compareTo(s)){
				personNames.add(i, name);
				return;
			}
		}
		personNames.add(name);
	}
}
Download

Comments

Popular posts from this blog