// Storing input strings in alphabetical order.
// Elena's solution
// need this import for reading data:
import java.io.*;
import java.util.*;
public class VectorAlphabet {
public static void main (String [] args) throws IOException {
// Create a buffered reader
// need only one buffered reader for all your reading
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// string for storing a line of input
String line;
System.out.print("Please enter a string: ");
line = in.readLine();
Vector v = new Vector();
while (!line.equals("bye")) {
int size = v.size();
int index = size; // index at which the string will be inserted
// initially set to size (the string is inserted at the end)
// the loop to find the correct place to insert
for (int i = 0; i < size; ++i) {
String current = (String) v.elementAt(i);
// if line goes before current in aplphabetical
// order, it should be inserted at the current index
// the condition index == size guarantees that
// the index is set only once -- the first time
// line.compareTo(current) < 0 is true
if (line.compareTo(current) < 0 && index == size) {
index = i;
}
}
// inserting the string at the correct index
v.add(index, line);
System.out.print("Please enter a string: ");
line = in.readLine();
}
int size = v.size();
for (int i = 0; i < size; ++i) {
System.out.println(v.elementAt(i));
}
}
}
This is an example from CSci 1211 course.