Free University of Bozen-Bolzano
Bachelor in Production Engineering
Introduction to Programming - A.A. 2005/2006
Exam exercise
Class Buffer
A Buffer is an object that represents a zone of memory that
temporarily stores data items. For simplicity, we assume that each data item
is a float. A Buffer has a limited capacity, corresponding to the
number of data items it can store. Buffer objects support the
following functionalities:
- creation: that, given an integer c, creates a
Buffer object with capacity c containing 0
data items;
- remainingCapacity: that returns the remaining capacity of the
Buffer;
- numDataItems: that returns the number of data items present in
the Buffer;
- addDataItem: that, given a data item d (represented by
a float), adds the data item to the end of the Buffer, if the
Buffer has sufficient remaining capacity to store the data item;
otherwise it does nothing;
- extractDataItem: that, given an integer i between
0 and numDataItems()-1, returns the data item in
position i and eliminates it from the Buffer; the
positions of all data items following the one in position i are
decreased by 1; if the integer i is not between 0 and
numDataItems()-1, a message is printed, the buffer is not
modified, and 0 (as a float) is returned;
- countOccurrences: that, given a data item d,
returns the number of times that such a data item is present in the
Buffer;
- whichPositions: that, given a data item d, returns an
array of integers of proper size containing the positions in the
Buffer of the occurrences of the data item d.
Part 1.
Write a Java class Buffer
to represent Buffer objects.
Solution:
representation of the
objects,
skeleton of the class,
class Buffer
Part 2.
Realize a static method client of the class Buffer
that reads
from standard input an integer c and then c/2 floats, and returns
a Buffer
object with initial capacity c and containing as
data items the floats read from standard input in the order in which they are
read. Before each read operation an appropriate message should be printed on
standard output.
Solution
Part 3.
Describe the notions of local variable and of instance
variable, and illustrate specifically the concepts of scope and
lifetime.