import java.util.Scanner; public class WordSeq { final int INIT_SZ = 5; // the initial array size String[] sequence; // where we store values int next; // next available index /** * Allocates an initial array. */ public WordSeq() { sequence = new String[INIT_SZ]; next = 0; } /** * Appends a word to the WordSeq. * @param word The word. */ public void append(String word) { if (next == sequence.length) { expand(); } sequence[next] = word; next++; } /** * Returns a string representing the entire sequence. * @return Stringified sequence. */ public String toString() { String s = ""; for (int i = 0; i < next; i++) { s += sequence[i] + " "; } return s; } /** * Doubles storage, copies elements, and * replaces the original array. */ private void expand() { // Uncomment this line if you want to see when we expand: // System.out.println("DEBUG: expanding!"); String[] sequence2 = new String[sequence.length * 2]; for (int i = 0; i < sequence.length; i++) { sequence2[i] = sequence[i]; } sequence = sequence2; } /** * Prompts the user to enter a word. If the entered word is not 'exit', * then it stores the word in the given WordSeq and returns true. * Otherwise, it returns false. * @param s A scanner to read input * @param ws The sequence with which to append * @return False iff the user wants to quit. */ public static boolean promptUser(Scanner s, WordSeq ws) { System.out.print("Enter a word (or 'exit' to quit): "); String word = s.next(); if (word.equals("exit")) { return false; } else { ws.append(word); return true; } } /** * Ask the user for a bunch of words. When the user * types 'exit', print the sequence and quit. * @param args command-line arguments, ignored */ public static void main(String[] args) { Scanner s = new Scanner(System.in); WordSeq ws = new WordSeq(); while (promptUser(s, ws)) {} System.out.println(ws); } }