Thursday, February 19, 2009

Tues Feb 24: arrays and vectors, part two

OK, so now we've got "back in the saddle" with Arrays. Now it's time to combine what we just (re)learned with something we looked at just before the vacation: getting a number from a TextField, and making use of it.

You may recall that there is a method called "Integer.parseInt( )" which allows you to take what looks like an integer from a TextField, and make it a real honest to GOD int. Kind of like changing Pinocchio from a puppet to a real boy. What we will do here with our program is to create a TextField, get an int value from it, assign that value to an int variable, and then use that variable to choose an element from our array. Here we go:

A) just below where you set up your Array, declare a TextField and an int variable, like so:
TextField whichOne; int whichQuote;

B) inside the constructor, just below the button we just created, create the TextField, like so:
whichOne = new TextField("type in an integer from 0 to 2"); Area52.add(whichOne);

C) in the "else if" for your "show" button, add these lines of code:
//get number from TextField and change it to an Integer whichQuote = Integer.parseInt(whichOne.getText() ); //pick out that element from array & print it to System console System.out.println(quotes[whichQuote]);

Recompile, then run the program. See if you can choose which element of the array will print out to the System console!

Cheers,
Uncle Paulie

No comments:

Post a Comment