- Tell whether each of the following will produce a compile-time error,
a runtime error, or no error. If there is an error, explain why; if
no error, tell what the code will print.
a) String[] names;
System.out.println(names[0]);
b) String[] names;
names = new String[10];
System.out.println(names[5]);
c) String[] names;
names = new String[10];
System.out.println(names[5].length());
d) String[] names;
names = new String[10];
for (int i=0; i<10; i++)
names[i] = "joe" + i;
System.out.println(names[5]);
e) String[] names;
names = new String[10];
for (int i=0; i<10; i++)
names[i] = "joe" + i;
System.out.println(names[5].length());
- Write a method boolean findCD(CD cd)
for the CDCollection class on p. 388-390 of the text. This method should
take a CD object and return true if that CD is in the collection,
false otherwise. You don't want look
through the array any longer than you have to - think carefully about what kind of loop to use!
Important: Assume that you have already added a
public boolean equals(CD cd) method to the CD class (p. 391) that
returns true if two CDs are considered equal.
- We talked about accessing rows and columns in a two dimensional array.
If the array is a square, we can also talk about its diagonals. The main
diagonal goes from the upper left corner to the lower right corner, and the
other diagonal goes from the lower left corner to the upper right. So in
the square below, the elements of the main diagonal from left to right
are 1 6 11 16
and the elements of the other diagonal are 13 10 7 4.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
- Write code that prints the elements of the main diagonal, one per line,
for a two-dimensional array a.
- Write code that prints the elements of the other diagonal, one per line,
for a two-dimensional array a. Careful; this one is trickier!