/* * Using vectors: an example * * Laura Toma * csci 210 * */ import java.util.Vector; import java.util.Scanner; class VectorExample { public static void main(String[] args) { /* create a new vector; we could specify an initial size, if * we have a good guess; in this case we don't. Note that we * don't know the type of the elements in v; Java will accept * anything */ Vector v = new Vector (); /* the preferred way (does not generate warnings) is to specify * the type of the elements in the vector. * * Vector v = new Vector(); * * this tells java it is a vector if elements of some type T * In our case: v is a vector of Strings * Vector v = new Vector(); */ //create a scanner to read from standard input (terminal) Scanner sc = new Scanner(System.in); System.out.println("Enter words, all on one line. Press retyrn when done: "); //read a line from user String line = sc.nextLine(); //we'd like to split the line into words, so we create a //scanner to read fro the line Scanner linesc = new Scanner (line); while (linesc.hasNext()) { String nextWord = linesc.next(); v.add(nextWord); //these are debugging prints //System.out.print("next token: " + nextToken + ": adding to vector. "); //System.out.println("size=" + v.size()); } //when printing a Vector, the method toString is called. //Vector overrides toString() to print a lits of its elements System.out.println("The vector is: " + v); System.out.println("size=" + v.size() + " capacity=" + v.capacity()); } }