Computer Science AP - Lab 17
For the following code segments, write
down (on paper) solutions to the problems, or the missing sections in
order to make them work as they
are described. Do not print this page, nor your answers.
Write them with pen or pencil as neatly as possible (for practice on
the AP exam)
1)
Write code to declare an integer array
that is foo elements large
int[] schnookielumps
= new int[foo];
2)
Write code to declare an ArrayList
of Strings consisting of the Strings "foo", "bar", and "baz"
ArrayList anarray = new ArrayList();
anarray.add("foo");
anarray.add("bar");
anarray.add("baz");
3)
Write code to declare a two dimensional
array of Strings that has 10 columns, and 25 rows
String[][] fenchurch = new
String[10][25];
4)
Write a comment to describe what is
happening with the following code:
int total = 0;
for (int a = 0; a < arr.length; a++) {
total = total + arr[a];
}
// total becomes the total of all
elements in array arr
5-9) Fill in the blanks according to the comments to
make the code work correctly
// the following code reads in a series
of Strings from the user, and then displays what the user entered back
to the user
String input = "";
ArrayList a = new ArrayList();
// keep on looping as the user has not typed the word QUIT
while (!input
.equals("QUIT")) {
// #5
input =
JOptionPane.showInputDialog("Enter in a String (QUIT to end)");
// add in the input to the end of the arraylist
a.add(input); // #6 or
a.add(a.size()-1,input);
}
// now remove the word QUIT from the ArrayList (it will be the last
entry, and remember indices start counting from 0
a.
remove(a.size()-1); // #7
// now go through each element of the ArrayList
for (int b = 0; b <
a.size();
b++) { // #8
// now display the String
as a String at index b from the ArrayList
JOptionPane.showMessageDialog(null,
(String)
a.get(b)); // #9
}
10) Explain why you cannot directly place integers into an
ArrayList
ints are not Objects, nor do they
extend Objects in any way, and ArrayList can only store Objects or
classes extending Object.