Thursday, February 19, 2009

Tues Feb 24: arrays and vectors part three

OK, now for the new stuff: we are going to create and use a VECTOR (cue dramatic theme music!). A Vector is like an Array, only you can add elements to it while the program is running. You can also subtract elements, or change the value of elements, all while the program is running. It's like having an array with an elastic waistband: very stretchy, very useful. So let's add one, OK?

A) the first step is to add an import statement at the very top of your program; vectors come from quite a different country than arrays:
import java.util.*;

B) just below where we declared our int variable, declare your Vector:
Vector vNess;

D) just below declared the "show" button, declare another button:
Button howMany; //a button to see how big our Vector is

E) in the constructor, just below where we created that TextField, create both the button and the Vector, like so:
howMany = new Button("how Many?");
howMany.addActionListener(this);
Area52.add( howMany);

vNess = new Vector(3);

F) Lastly, add another "else if" to our actionPerformed, like so:
else if (e.getSource() == howMany)
{
System.out.println("Vector vNess has this capacity " + vNess.capacity() );
System.out.println("Vector vNess is this big " + vNess.size() );
}//size and capacity of vector?


Re-compile the program, and run it to see if your new button works. In the next segment, I'll explain the difference between "size" and "capacity" for those of you who are struggling to get a grasp on that.

Cheers,
Uncle Paulie

No comments:

Post a Comment