0

I have the following code, and I have sort the array list alphabetically in the main method, as the user inputs his strings. Here is my code:

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

class Main{
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(System.in);
    String name;
    do{
      System.out.println("Enter the next name: ");
      name = scan.nextLine();
      String toUpperCase = titleCase(name);
      if(!toUpperCase.equals("Stop")){
        names.add(toUpperCase);
      }
    } while(!name.equalsIgnoreCase("STOP"));

    System.out.println(names.toString());


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    return output;
  }
}

Please don't give any generic answers, I've been struggling with this for a while now. If the answer seems simple to you, it probably isn't for me.

8
  • Can you use a TreeSet? Otherwise, write a sort method. Commented Mar 29, 2016 at 14:16
  • 6
    Is the goal to write your own sort method or is the goal to maintain a sorted data structure? Commented Mar 29, 2016 at 14:17
  • As @andrewdleach said, if the data needs to be sorted after adding all the names write your own sort function, else add new names alphabetically by traversing the list every time. Commented Mar 29, 2016 at 14:20
  • I'm not sure what you mean by this, all I was told in the assignment is this: Commented Mar 29, 2016 at 14:21
  • In the main method: Ask the user to input names, and as the names are input they will be added in alphabetical order to an ArrayList. Commented Mar 29, 2016 at 14:21

4 Answers 4

2

replace this line:

names.add(toUpperCase);

with this:

int index = names.size();
for (int i = 0; i < names.size(); i++) {
    if (names.get(i).compareTo(toUpperCase) > 0) {
        index = i;
        break;
    }
}
names.add(index, toUpperCase);

so, every time you have new string from user - you will insert it into proper position of your array list

this method is quite slow, but ok for home assignment

Sign up to request clarification or add additional context in comments.

3 Comments

you are a gods send, bless you sir
A binary search would be better for a long list.
With respect to @user2963623's comment, check out Collections.binarySearch.
1

As suggested in the comments, the most simple way of maintaining a sorted data structure upon each insert is to use a TreeSet or any other data structure that maintains sorted order internally. Instead of declaring an ArrayList<String> you would simply need to modify your code to this:

Set<String> names = new TreeSet<>();
Scanner scan = new Scanner(System.in);
String name;
do {
  System.out.println("Enter the next name: ");
  name = scan.nextLine();
  String toUpperCase = titleCase(name);
  if(!toUpperCase.equals("Stop")){
    names.add(toUpperCase);
  }
} while(!name.equalsIgnoreCase("STOP"));

From Javadocs for TreeSet:

the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Comments

0

Please try below code. You can replace the sorting algorithm with more efficient algorithm like merge sort/selection sort etc..

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

class alsort{
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(System.in);
    String name;
    do{
      System.out.println("Enter the next name: ");
      name = scan.nextLine();
      String toUpperCase = titleCase(name);
      if(!toUpperCase.equals("Stop")){
        names.add(toUpperCase);
      }
    } while(!name.equalsIgnoreCase("STOP"));

    System.out.println(names.toString());

    for(int i=0;i<name.length();i++){
        for(int j=i;j<=name.length();j++){
            if(names.get(i).compareTo(names.get(j))>0){
                String tmp=names.get(i);
                names.set(i, names.get(j));
                names.set(j, tmp);
            }
        }
    }

    System.out.println(names.toString());


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    return output;
  }
}

Comments

0
public class SortedArrayList<T> extends ArrayList<T> {

        /**
     * 
     */
    private static final long serialVersionUID = 1L;


        @SuppressWarnings("unchecked")
        public void insertSorted(T value) {
            add(value);
            Comparable<T> cmp = (Comparable<T>) value;
            for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
                Collections.swap(this, i, i-1);
        }


    public static void main(String[] s){        
        SortedArrayList<String> myList = new SortedArrayList<String>();

        myList.insertSorted("ddd");   
        myList.insertSorted("aaa");
        myList.insertSorted("xyz"); 
        System.out.println(myList);     
    }



}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.