Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Lab Time: ArrayLists
Do the same exercise for ArrayLists that we did for Arrays..
- Make a Java class with arrays and loops.
- Declare and initialize an ArrayList object.
- Use JOptionPane.showInputDialog("prompt text"); to ask the user
how many pets he or she has.
- Then, loop through the ArrayList, using
JOptionPane.showInputDialog to ask
the user for his or her pets' names.
- Add each name to the ArrayList with the add() method.
- Finally, print them out, using a for loop.
- Notes:
- You can do this all in one method if that makes it easier.
- Don't forget to have a public static void main(String
args[])
method that will be called from the command line and will instantiate
an
object of your class.
- import javax.swing.*; at the very top of the program.
This will
allow
you to use the JOptionPane class in your program.
- import java.util.*; at the top of your program. This will
allow you to use the ArrayList class.
- The prompt to ask the number of pets should be outside and
before
your first loop. This will tell you how many times to loop, so
you
should know this ahead of time!
- Assuming your ArrayList is named pets, the prompt and
assignment should look something like this:
String petName = JOptionPane.showInputDialog("Enter the name for
pet
" + (i + 1) + ":");
pets.add(petName);
- This should be in the body of a for loop, and i should be the
counter
variable.
- Use another for loop to print out the names. Thus, you
should
have
two for loops total.
- Look at previous examples, or ask me for help!
Stuck? See the solution here.
Created by: Brandan
Jones January 4, 2002