Free University of Bozen-Bolzano
Faculty of Computer Science - Bachelor in Applied Computer Science
Introduction to Programming - A.A. 2004/2005
Exam exercise
Class Wardrobe
We want to manage information on a wardrobe. Each clothing item in the
wardrobe is identified by a code (a string). A Wardrobe can contain
an arbitrary number of hooks, numbered sequentially starting from 0. Each hook
in the wardrobe can be empty or occupied by an item. The Wardrobe
objects support the following functionalities:
- creation: that, given an integer n, creates a
Wardrobe object that initially has n hooks that are
all empty;
- getNumHooks: that returns the number of hooks of the wardrobe;
- assignHook: that, given the code c of an item (a
string), occupies the first empty hook (i.e., the empty hook with the
smallest number) with the item c and returns the number of the
hook, if there is an empty hook; if there is no empty hook, then an
exception is thrown;
- emptyHook: that, given the number n of a hook, makes
hook n empty;
- getItem: that, given the number n of a hook, returns
the code of the item currently occupying hook n, if the hook is
occupied; null otherwise;
- searchItem: that, given the code c of an item, returns
the number of the hook occupied by the item c, if it exists; -1
otherwise;
- getNumOccupiedHooks: that returns the number of occupied hooks
in the wardrobe;
- addHooks: that, given a positive integer n, adds to
the wardrobe n empty hooks numbered sequentially starting from
the last empty hook already present in the wardrobe;
- reorderWardrobe: that rearranges the items in the wardrobe in
such a way that all hooks up to a certain number are occupied, and
eliminates from the wardrobe the remaining hooks.
Part 1.
Write a Java class Wardrobe
to represent Wardrobe
objects.
Solution:
representation of the
objects,
skeleton of the class,
class Wardrobe
Alternative solution:
representation of the
objects,
skeleton of the class,
class Wardrobe2
Part 2.
Realize a static method saveItemAssignment
, client of the class
Wardrobe
that, given a wardrobe g and the name f
of a file, writes on the file f, one per line, the number of the hook
and the code of the item that occupies it, for all occupied hooks in the
wardrobe g.
Solution
Alternative solution
Part 3.
Describe how memory is managed when methods are activated and when their
activation terminates. Specifically, describe how parameter are passed and how
the return value is returned. Illustrate the mechanism of memory management on
the example of the activation of x = factorial(3);
in a method
main
, where x
is a local variable of
main
and factorial
is a method, implemented using
recursion, to calculate the factorial of a nonnegative integer.