In today's lesson, we are going to work with our old friend the Array --yup, they got 'em in Java too!-- and his close personal friend, the Vector. But before we go any further, let's get you a copy of the starting program we will use to explore this new concept; go to this folder and download the file inside:
http://www.box.net/shared/knh8a5evxt
OK, you got it? Good; let's get going!
If you recall, we met the Array way back in the fall. An Array is just a collection of variables that are grouped together. In most languages, all the elements of the Array are the same type. To make it simpler, we will be using a String Array, plus a TextField, plus a Button for retrieving elements of that array and putting them into the TextField. Here's how we do it:
A) First off, let's add an Array, and put some elements in it (do it under the place where declared the "exit" button):
String quotes[] = {"hello","hola","bonjour"};
B) next, let's declare a button just below that Array, so we can stuff with our new Array:
Button show;//a button for playing with arrays
C) The next step is to add that button to your frame, and give it an ActionListener. You can see how to do that from the button that's already in the program; so just add this new Button named "show" in the same way and inside the constructor.
D) Lastly, you'll need to say what that new button will do with your Array. You will need to add an "else if" statement below the first "if". Here is what I made my button do:
else if (e.getSource() == show)
{
System.out.println(quotes[0]);
}// show the quote
Essentially, I took the zero element in the array (that would be the very first element, kimo sabe) and printed it to the System console.
OK, see if you can make that happen!
Uncle Paulie
Thursday, February 19, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment