Instructor: Dan Shiovitz
Name: _____________________________________________________________
Mean around 23, which is good, since we've seen at least half this before.
[6 points total - 1 each] Is the statement below true or false? Circle one:
new
. null
. If you want the objects, you'll have to
new
them yourself.box[6]
refers to
the sixth element of box
(assume
box
is an array that contains ten elements)int
s is int
.
initializer list
.
Pretty straightforward if you know the syntax:
int[] intArray = { 10, 11, 12, 13, 14, 15 };(Notice this way does not use
new
.)
Letters
of
unknown size has been instantiated and had values
filled in. Write a code fragment to print out
every other elements of Letters
(i.e., print out the first, third, fifth, and so on, but not
the second or fourth)
The important concept here is that all arrays have a
length
member, which is public
and
final
. The value that's in length
is
the actual length of the array, not the last usable index
in it.
for (int i = 0; i < Letters.length; i += 2) System.out.println(Letters[i]);
Write a class named Carrots
that simulates a
field of carrots. Full credit will require good use of
encapsulation. This class has the following methods:
class Carrots { private int currentNum; private int lastEaten; public Carrots() { currentNum = 20; lastEaten = 0; } public Carrots(int newCurrent, int newEaten) { currentNum = newCurrent; lastEaten = newEaten; } public int carrotCount() { return currentNum; } public void getEaten() { currentNum -= ++lastEaten; if (currentNum < 0) currentNum = 0; } }
Write a code fragment that creates a Carrots
object
(with N carrots initially, and 1 carrot eaten last (you may
assume N is an integer that has been declared and
initialized)), and then repeatedly calls the mutator method until the
carrots are all gone. Each time before decreasing the number of
carrots, you should print out the current total. When there are no
carrots left, print out "The End".
Carrots McGregor = new Carrots(N, 1); while (McGregor.carrotCount() > 0) { System.out.println("There are " + McGregor.carrotCount() + " carrot(s) in the field"); McGregor.getEaten(); } System.out.println("The End");